tags:

views:

68

answers:

2

I have seen people define their events like this:

public event EventHandler<EventArgs> MyEvent = delegate{};

Can somebody explain how this is different from defining it without it? Is it to avoid checking for null when raising the event?

+2  A: 

This declaration ensures that MyEvent is never null, removing the tedious and error-prone task of having to check for null every time, at the cost of executing an extra empty delegate every time the event is fired.

JSBangs
+10  A: 

You got it - adding the empty delegate lets you avoid this:

public void DoSomething() { 
    if (MyEvent != null) // Unnecessary! 
        MyEvent(this, "foo"); 
} 
Paul Kearney - pk