VB.NET vs C# – Event handling

Basic concept of the events is simple:
Class can raise an event. User of the class can subscribe to the event and react to it using delegate functions.

For example, handling the click event of a button. Button is named btnOK, delegate function is named btnOK_Click.

Subscribing:

//C#
btnOK.Click += new EventHandler(btnOK_Click);
'VB.NET
AddHandler btnOK.Click, AddressOf btnOK_Click

That’s very similar but this is also where similarities end. Now for the differences:

VB – Syntactic sugar:

Instead of manually attaching to the event, you can decorate the handler function with Handles keyword:

Private Sub btnOK_Click(...) Handles btnOK.Click

With that you don’t have to worry about adding or removing the handler and it’s obvious what this method is doing and what it handles. One method can handle multiple events of the same signature.

Private Sub txt_Validating(...) Handles txtName.Validating, txtNumber.Validating, txtDate.Validating

C# – IDE feature:

After writing “btnOK.Click +=” IDE will offer you to complete the statement for you (press TAB to insert “new EventHandler(btnOK_Click)”). Even better, after that it will offer you to create delegate sub if you press another TAB. Useful and unobtrusive, great feature.

VB – IDE feature:

If a variable is declared with WithEvents keyword (all UI controls created in designer are), you can select it from pull-down menu above the code and all events will be offered in another pull-down menu next to it. Clicking on the event automatically creates a delegate sub with Handles keyword.

C# – IDE problem:

Lack of handles keyword is problematic in C# when you create the event handler from UI designer. Double clicking a button automatically creates the delegate and attaches the event to it. Problem is that attacher code is hidden in autogenerated part of the code and you can’t see if handler is really attached which can lead to duplicate attachment or no attachment at all.

VB – feature:

You can just raise an event, if somebody will handle it, great, if not, no worries.

C# – feature:

You can check if any event is attached and raise only if there is.

Tags:

Leave a Reply