Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this event declared with an anonymous delegate?

Tags:

c#

events

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?

like image 463
John_Sheares Avatar asked Jun 09 '10 21:06

John_Sheares


2 Answers

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

public void DoSomething() { 
    if (MyEvent != null) // Unnecessary! 
        MyEvent(this, "foo"); 
} 
like image 188
Paul Kearney - pk Avatar answered Nov 16 '22 15:11

Paul Kearney - pk


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.

like image 2
JSBձոգչ Avatar answered Nov 16 '22 17:11

JSBձոգչ