Mimerafm Mimerafm - 4 years ago 144
Vb.net Question

what are the differences in terms of event handling between C# and VB?

First of all I just want you let you all know that this question is coming from a newbie so don't be too harsh on me.

As far as I know, in VB.net when you want a function or sub to be raised by an event all you have to do is add "Handles NameofTheEvent" at the end of it. Like this:

Public Sub Action1() Handles MyEvent

End Sub

Public Sub Action2() Handles MyEvent

End Sub

However in C#, first you'll have to declare a delegate, then define an event as your delegate and finally add delegates that point to those methods to the event. Like this:

public delegate void MyDelegate();
public static event MyDelegate MyEvent = new MyDelegate(Action1) + new MyDelegate(Action2);
public void Action1()

public void Action2()


It seems to me that the way VB.net handles this in a much more tangible manner. Honestly, I don't even understand why the + operator should even work in new MyDelegate(Action1) + new MyDelegate(Action2)... It makes no sense to me.

Having said that, I suspect maybe there are some hidden benefits to the way C# handles this. So my questions are, are there actually any hidden benefits and if yes what are these potential benefits?

Answer Source

None of them is significantly better than the other one. They are different languages with different syntax, which, by the way can be converted from one into the other, so under the hood there should not really be many differences.

The + operator between delegates in C# is concatenating delegates. To put it into simple words, it means that Action1 and Action2 should be executed when the event is triggered. In VB you are writing the same more verbosely.

If we have to choose, I would choose C#, but not because its event handling. My reasons would be that:

  • C# is C-based, like many other languages
  • C# has the ; separator, not a white space
  • C# code is less verbose, you have to spend less time with typing
  • C# has certain advantages, for example the well-known Date vs. DateTime issue

But these are my subjective preferences.


@Pieter Witvoet's contribution is:

If you don't like custom delegates in C# then you can use Action<> and Func<> (you lose the ability to give arguments meaningful names, though). If you want to register or unregister an event handler at any time you can use the += and -= operators.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download