-3

I am trying to understand events in C#.
I want to convert code from VB.NET to C# but I cannot succeed.
Can you please help me in converting the following code from VB.NET to C#?
I will appreciate your help.

Module Module1

    Class PersonClass

        Public Event nameChanged(ByVal aName As String)

        Public _Name As String
        Public Property Name() As String
            Get
                Return _Name
            End Get
            Set(ByVal value As String)
                _Name = value

                RaiseEvent nameChanged(value)
            End Set
        End Property
    End Class

    Dim WithEvents p As PersonClass

    Sub Main()

        p = New PersonClass

        p.Name = "George"
        Console.ReadLine()
    End Sub

    Sub p_nameChanged(ByVal aName As String) Handles p.nameChanged
        Console.WriteLine("{0} name changed to : {1}", Date.Now.ToString("dd-MM-yy hh:mm:ss"), aName)
    End Sub
End Module
Miro J.
  • 4,270
  • 4
  • 28
  • 49
Bill
  • 21
  • 2

1 Answers1

-1

The link to understanding C# delegates and event will help answer any questions.

Here's code that models the VB code:

using System;

// C# events start with declaring a delegate
public delegate void PersonNameChangeEvent(string oldName, string newName);

public class Person
{
    // I noticed an oddity in the VB code, in that the data member was
    // public.  It should be private, especially since there is a property
    // handler for it
    private string name;
    public string Name
    {
        get { return name;}
        set
        {
            string old = name;
            name = value;

            PersonNameChangeEvent notifyEvent = OnNameChange;
            if (null == OnNameChange)
               return;

            notifyEvent(old, name);
        }
    }

    // a delegate instance is a class member
    public event PersonNameChangeEvent OnNameChange;    
}


public static class Test
{
    public static void Main(string[] args)
    {
         Person p = new Person();

         // assign a method by using of a lamda expression to the event/delegate
         // this expression will get called in the setter of Person.Name....
         // see notifyEvent(old, name)
         p.OnNameChange += ((o, n) => { Console.WriteLine(string.Format("Person '{0}' changed to '{1}'", o, n));  } );

         p.Name = "Bob";
         p.Name = "Joe";
    }
}

Not sure what explanation you would like. Please ask and I will do my best to answer.

tatmanblue
  • 1,176
  • 2
  • 14
  • 30