Search code examples
c#eventsdelegatesevent-handlingobserver-pattern

What is the event handler check for not being null?


In the code of all answers to question:

there is a check for EventHandler handler not being null

EventHandler handler = this.somethingHappened;  
if (handler != null)  
{  
   handler(this, EventArgs.Empty);  
}  

with subscription:

 observable.SomethingHappened += observer.HandleEvent;

as well as in articles, tutorials, examples, etc. on the internet.
Though I cannot grasp when and how this handler can happen to be null.

I've read over the answers to similar questions:

but I still could not grasp how in such kind of examples and illustrations the handler can happen to be null.

Can anybody explain me how the handler in this code can happen to be null?


Solution

  • Quite simply, if no delegate has yet been assigned to a particular event handler, it will be null, and trying to invoke it will cause a NullReferenceException.

    Doing a null check before invoking it prevents this NullReferenceException from occurring.