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:
PropertyChanged?.Invoke(this, args);
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
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);
}
}
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