In C#, you do something like this:
if (Changed != null)
Changed(this, EventArgs.Empty);
But what do you do in VB.NET?
There is RaiseEvent
, but is
RaiseEvent Changed(Me, EventArgs.Empty)
actually checking that something has subscribed to the event?
Unlike its C# equivalent,
RaiseEvent
in VB.NET will not raise an exception if there are no listeners, so it is not strictly necessary to perform the null check first.But if you want to do so anyway, there is a syntax for it. You just need to add
Event
as a suffix to the end of the event's name. (If you don't do this, you'll get a compiler error.) For example:Like I said above, though, I'm not really sure if there's any real benefit to doing this. It makes your code non-idiomatic and more difficult to read. The trick I present here isn't particularly well-documented, presumably because the whole point of the
RaiseEvent
keyword is to handle all of this for you in the background. It's much more convenient and intuitive that way, two design goals of the VB.NET language.Another reason you should probably leave this to be handled automatically is because it's somewhat difficult to get it right when doing it the C# way. The example snippet you've shown actually contains a race condition, a bug waiting to happen. More specifically, it's not thread-safe. You're supposed to create a temporary variable that captures the current set of event handlers, then do the null check. Something like this:
Eric Lippert has a great blog article about this here, inspired by this Stack Overflow question.
Interestingly, if you examine disassembled VB.NET code that utilizes the
RaiseEvent
keyword, you'll find that it is doing exactly what the above correct C# code does: declares a temporary variable, performs a null check, and then invokes the delegate. Why clutter up your code with all this each time?A direct conversion would be:
However
RaiseEvent
has to be used to raise events in VB.NET, you cannot simply call the event. No exception is thrown usingRaiseEvent
if there are no listeners.See: http://msdn.microsoft.com/en-GB/library/fwd3bwed(v=vs.71).aspx
Therefore the following should be used: