.NET Event Collection and NullObject Pattern

We can raise an event in two ways:

public event EventHandler MyEvent; private void DoSomething() { ... var handler = MyEvent; if (handler != null) handler(this,EventArgs.Empty); } 

and

 public event EventHandler MyEvent = (o,e) => {} ; private void DoSomething() { ... MyEvent(this, EventArgs.Empty); } 

I prefer the latter. It is shorter.
My colleagues insist on the first option.

Is there an advantage to the first over the second?

+6
source share
1 answer

Update for C # 6

In C # 6, you just use a null condition statement:

 PropertyChanged?.Invoke(this, args); 

This is recommended by Roslyn Wiki.

Original answer

Eric Lippert is a great event and race blog post that you should read if you haven’t.

The first option can be considered safer than the second, because the event can get null. Someone can casually modify a class. Also, if you deserialize instances, the second method will not work (depending on the serialization mechanism used).

Sometimes I use a helper method to create events

 static class Raiser { public static void Raise<T>(this EventHandler<T> evnt, object sender, T args) where T : EventArgs { if (evnt != null) { evnt(sender, args); } } } class SomeClass { public event EventHandler<EventArgs> MyEvent; private void DoSomething() { MyEvent.Raise(this, EventArgs.Empty); } } 
+11
source

All Articles