Search code examples
c#vb.netcode-conversion

How to translate from C# to VB.net


For a project written in VB.net I want to use the PropertyChangeNotifier class from this article, at least I'd like to try if it can help.

Since the original class is written in C# I tried to translate this class to VB.net, but one function I can'T get to compile and I don't know why, maybe you can help.

The original function in C# is:

private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    PropertyChangeNotifier notifier = (PropertyChangeNotifier)d;
    if (notifier.ValueChanged != null)
        notifier.ValueChanged(notifier, EventArgs.Empty);
}

My (slightly altered) translation (and the automatic translation of several web sites) is:

Private Shared Sub OnPropertyChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
    Dim notifier As PropertyChangeNotifier

    notifier = TryCast(d, PropertyChangeNotifier)
    If (notifier Is Nothing) Then
        Exit Sub
    End If

    RaiseEvent notifier.ValueChanged(notifier, EventArgs.Empty)
End Sub

If I remove the RaiseEvent the compiler tells me, that ValueChanged is an event and can't be called directly, I should use RaiseEvent. But when I use RaiseEvent the compiler tells me

'notifier' is not declared. It may be inaccessible due to its protection level.

But as ylou can see notifier is declared a few lines up.


Solution

  • I found a solution myself. It's not explaining the error messages, but at least it's compiling and hopefully working afterwards.

    I just added this to the class itself:

    Private Sub OnValueChanged(sender As Object, e As EventArgs)
        RaiseEvent ValueChanged(sender, e)
    End Sub
    

    And then instead of raising the event myself in the function OnPropertyChanged, I call my new procedure:

    Private Shared Sub OnPropertyChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
        Dim notifier As PropertyChangeNotifier
    
        notifier = TryCast(d, PropertyChangeNotifier)
        If (notifier Is Nothing) Then
            Exit Sub
        End If
    
        notifier.OnValueChanged(notifier, EventArgs.Empty)
    End Sub