0

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?

Community
  • 1
  • 1
Fulproof
  • 4,466
  • 6
  • 30
  • 50

1 Answers1

2

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.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • But it is being assigned in all such examples – Fulproof Feb 03 '13 at 18:08
  • No, it is being copied from another delegate. The value that was copied *can* be null. The reason it is copied is to take a snapshot of the invocation list, so that there is no risk that the delegate becomes null between the null check and the invocation. Simple rule of thumb... if there's nothing in the invocation list of an event, the value is null. – spender Feb 03 '13 at 18:10
  • Yes, as @spender says, if `this.somethingHappened` is `null`, then `handler` will be `null` too. – JLRishe Feb 03 '13 at 18:20