We can raise 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 last one. It is shorter.
My colleagues insist on the first variant.
Is there any superiority of the first over the second one?
Update for C# 6
In C# 6 you simply use the null-conditional operator like so:
This is recommended by the Roslyn wiki
Original Answer
Eric Lippert has a great blog post on Events and Races, which you should read if you haven’t.
The first option could be considered safer than the second because the event could get set to null. Someone could carelessly modify the class. Also, if you deserialize instances the 2nd method won’t work (depending on the serialization mechanism you use).
I sometimes use a helper method to raise events