Samson Bujju
Samson Bujju

Reputation: 625

Why not check for null like c# when raising custom events in vb.net?

I am looking at this page which talks about raising events. In here for c# syntax, it checks if the event is null and then raises the event. Why is not the same for vb.net?

public event CommandEventHandler ProductSelectionChanged;

In some method this is called.

if (ProductSelectionChanged != null)
{
    ProductSelectionChanged(this, e);
}

In vb it's raise event. Why is the difference. Also, this page talks about using this

Protected WithEvents products As DisplayProductSelection.

I tried it without this and event was handled. Is it a good practice to use this?

Upvotes: 1

Views: 163

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564771

The VB.Net RaiseEvent statement internally performs the Nothing (null) check for you. This is not done in C#, and must be handled manually. Note that many other languages, such as F# and C++/CLI, also don't require the manual null check.

This is often nicer, with the rare exception being if you want to have special logic which handles the case of the event having no subscribers (ie: and else branch), in which case the VB.Net Team has blogged about one approach to handle that scenario.

Upvotes: 3

Related Questions