10

I'm migrating some code from VB.NET to C# (3.5).

I find structures like:

Public Event DataLoaded(ByVal sender As Object, ByVal e As EventArgs)

Protected Sub Mag_Button_Load_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Mag_Button_Load.Click
[..]
        RaiseEvent DataLoaded(Me, EventArgs.Empty)
End Sub
[..]

'Other Class
Private Sub LoadData(ByVal sender As Object, ByVal e As System.EventArgs) Handles oData.DataLoaded
[..]
End Sub

What is the most straightforward way to translate such behaviour to C#?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pistacchio
  • 56,889
  • 107
  • 278
  • 420

1 Answers1

12

I recommend using the Telerik Code Converter as a start.

C# does not have that easy automatic attaching of event handlers by means of the "Handles" keyword like VB.NET does.

//EventHandler declaration
public event EventHandler  DataLoaded;
protected void Mag_Button_Load_Click(object sender, EventArgs e)
{

    //Raise Event
    if (DataLoaded != null) {
        DataLoaded(this, EventArgs.Empty);
    }
}

Also, You need to assign your event handlers to the objects like this:

Button1.Click += Button1_Click;

protected void Button1_Click(object sender, EventArgs e)
{
  //do something.
}

However C# does have the succinct ability of doing this as well:

Button1.Click += (sender, e)=>
{
    //do something
}
Jose Basilio
  • 50,714
  • 13
  • 121
  • 117
  • 1
    I think you've either forgotten the => for a lambda expression in the last piece of code (or the delegate keyword and parameter types for an anonymous method). – Jon Skeet Apr 27 '09 at 16:57
  • 1
    Adding lambda expressions to events can be done in VB.NET as well, with the following monstrosity: `AddHandler Button1.Click, Sub (sender,e) 'do something here`, or `AddHandler Button1.Click, Sub (sender,e) 'do something here over multiple lines' End Sub` – Zev Spitz Aug 03 '13 at 21:21