I have seen various coding styles to fire events in C#. The first style consisting of the following:
-an event handler
public delegate void NumberReachedEventHandler(object sender,
NumberReachedEventArgs e);
-an event
public event NumberReachedEventHandler NumberReached;
-and the method to fire the event
protected virtual void OnNumberReached(NumberReachedEventArgs e)
{
if(NumberReached != null)
{
NumberReached(this, e);
}
}
The second style however, has a different method to fire the event:
protected virtual void OnNumberReached(NumberReachedEventArgs e)
{
NumberReachedEventHandler handler = NumberReached;
if(handler != null)
{
handler(this, e);
}
}
To me, it appears that one style checks if the "event" is null and the second style checks if the delegate is null. However, my understanding is that an event is just an instance of a delegate, so I am wondering if there are any advantages to either way of writing the code. If so, please explain. Thanks in advance.