VB to C# Conversion: Events RRS feed

  • Question

  • How would I write this in C#??  I'm not all that up to speed on events to begin with so the conversion is even more difficult to me than it ought need to be.

    Event ModuleCommunication(ByVal sender As Object, ByVal e As ModuleCommunicationEventArgs) Implements ModuleCommunication

    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click

    RaiseEvent ModuleCommunication(Me, objModuleCommunicationEventArgs)



    Wednesday, November 23, 2005 5:11 PM


  • I assume that

    Public Event ModuleCommunication ...
    is your event declaration so you would translate this to:

    public delegate void ModuleCommunication ( object sender, ModuleCommunicationEventArgs e);

    as the prototype for the event handlers.  This may have already been declared for you and if so then you don't need it.  Otherwise it normally sits outside any class definition and provides an easy way to create multiple events using the same arguments.

    In  any class that wishes to raise this event you would then add:

    public event ModuleCommunication eventName;

    where eventName is the name of the event as you want it exposed from your class (say MyEvent).

    To raise the event do the following:

    //Handler for btnSend.Click that you previously set up using
    // btnSend.Click += OnClick;
    private void OnClick ( object sender, EventArgs e )

    private void OnModuleCommunication ( ModuleCommunicationEventArgs e )
       if (eventName != null)
          eventName(this, e);

    Technically the OnModuleCommunication is not needed but it does encapsulate the code needed to raise the event.

    To add a handler for an event the syntax is:

    obj.eventName += new eventHandlerType(funcName);

    where obj is the object that implements the event, eventName is the name of the event (MyEvent), eventHandlerType is the type of the delegate used to handle the event (in your case ModuleCommunication) and funcName is the method to invoke when the event is raised.  In C# 2.0 and above you can leave off the handler type like so:

    obj.eventName += funcName;

    Michael Taylor - 11/23/05
    Wednesday, November 23, 2005 6:51 PM