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); } }
source share