altaaf.hussein
altaaf.hussein

Reputation: 282

VB.NET to C# with Event Handlers

Hi all sorry but you must get this all the time, I have tried to search for it but could not find anything specific to what I am looking for.

Basically I pretty much know VB.NET fully and I use it constantly, something I want to get into is C# so I have decided to use my free time to try and get a grip on this. I am doing this by using one of my old VB.NET custom binary objects and converting it by hand (not really using a converter as I want to learn it rather than just converting it.) I am however using the internet to guide me. So far I am trying to create custom even handlers my previous VB.NET code was as follows;

Public Event BeforeExecution_Handler()

but doing it in C# seems to be a bit more trickier and i have made the following

public event BeforeExecution_HandlerEvent BeforeExecution_Handler;
public delegate void BeforeExecution_HandlerEvent(); 

No first is this correct, but secondly what is going on here, why do I have to create definitions for it twice. I am having a guess that the delegate section is where you put variables but why is it like this. Can somebody explain

Upvotes: 3

Views: 1619

Answers (1)

Matt Wilko
Matt Wilko

Reputation: 27342

In VB.NET you can implicitly create a delegate, so you can just do something like this:

Declaration:

Public Event MsgArrivedEvent(ByVal message As String) 'behind the scenes a delegate is created for you

Invocation:

RaiseEvent MsgArrived("foo")

In C# you have to use delegates.

Declaration:

public delegate void MsgArrivedEventHandler(string message);
public event MsgArrivedEventHandler MsgArrivedEvent;

Invocation:

MsgArrivedEvent("Test message");

Note that you can also explicitly create a delegate in VB.NET in the same way as C# but this is just more typing for no gain really:

Declaration:

Public Delegate Sub MsgArrivedEventHandler(ByVal message As String)
Public Event MsgArrivedEvent As MsgArrivedEventHandler

Invocation:

RaiseEvent MsgArrivedEvent("foo")

Also note that best practise is actually to use use a sender and EventArgs class (or a class inherited from it) as the parameters to the Event/Delegate:

public delegate void MsgArrivedEventHandler(object sender, EventArgs e);

Upvotes: 6

Related Questions