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?
You got it - adding the empty delegate lets you avoid this:
public void DoSomething() {
if (MyEvent != null) // Unnecessary!
MyEvent(this, "foo");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With