Suppose I have this:
class C {
public delegate void MyEventHandler();
public event MyEventHandler MyEvent;
public void foo() {
MyEvent(); // NullReferenceException?
}
}
Under what circumstances will trying to raise the event in the foo
method generate a NullReferenceException, and why?
The event will be null until an event handler is actually added to it. And,
it will be null after the last event handler is removed from it. The reason
is that the code that you posted really compiles to something that looks
a little more like this:
class C {
{
public delegate void MyEventHandler();
private MyEventHandler _MyEvent;
public void add_MyEvent(MyEventHandler value)
{
_MyEvent = (MyEventHandler)Delegate.Combine(_MyEvent, value);
}
public void remove_MyEvent(MyEventHandler value)
{
_MyEvent = (MyEventHandler)Delegate.Remove(_MyEvent, value);
}
public void foo() {
MyEvent();
}
}
An event compiles to a private field that holds your delegate instance and
two methods that add and remove handlers to and from the delegate. When the
class is created, the field is null. When a handler is added to the event,
Delegate.Combine() is called and that creates your delegate or adds the handler
to your delegate if it is already created. When a handler is removed from
the event, Delegate.Remove() is called and that removes the handler from
your delegate sets it to null if there aren't anymore handlers.
Best Regards,
Dustin Campbell
Developer Express Inc.