Monday, April 23, 2012

Is this a better way to fire/invoke events without a null check in C#?

Most code I have seen uses the following way to declare and invoke event firing:



public class MyExample
{
public event Action MyEvent; // could also be a event EventHandler<EventArgs>

private void OnMyEvent()
{
var handler = this.MyEvent; // copy before access (to aviod race cond.)
if (handler != null)
{
handler();
}
}

public void DoSomeThingsAndFireEvent()
{
// ... doing some things here
OnMyEvent();
}
}


Even ReSharper generates an invoking method the way mentioned above.



Why not just do it this way:



public class MyExample
{
public event Action MyEvent = delegate {}; // init here, so it's never null

public void DoSomeThingsAndFireEvent()
{
// ... doing some things here
OnMyEvent(); // save to call directly because this can't be null
}
}


Can anyone explain a reason why not to do this? (pro vs. cons)





No comments:

Post a Comment