Alex Rivera | Logout

Use of null check in event handler

Asked 2009-03-23T09:11:48.877
34

When checking if an event handler is null, is this done on a per-thread basis?

Ensuring someone is listening to the event is done like this:

EventSeven += new DivBySevenHandler(dbsl.ShowOnScreen);

If I add code following this pattern above where I check for null, then why would I need a null check (code taken from this site). What am I missing?

Also, what's the rule with events and GC?

c#
Edit
Report

1 Answer

-1

If you mean this:

public static void OnEventSeven(DivBySevenEventArgs e)
    {
        if(EventSeven!=null)
            EventSeven(new object(),e);
    }    

piece of code, then the answer is:

If nobody subscribes to the "EventSeven" event handler then you'll get a null-reference exception on "EventSeven(new object(),e);"

And the rule:

The subscriber is responsible for adding a handler (+=) and removing it (-=) when he doesn't want to receive the events any longer. Garbage collection goes by the default rules, if an object is no longer referenced it can be cleaned.

answered 2009-03-23T09:20:06.300

Your Answer