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?
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?
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.
You got it - adding the empty delegate lets you avoid this:
public void DoSomething() {
if (MyEvent != null) // Unnecessary!
MyEvent(this, "foo");
}