Wednesday, 26 March 2008

Safe event pattern

I've found this useful little pattern browsing the code of the latest Prism drop.
It looks like this:

public event EventHandler Updated = delegate { };

I've never declared events in my code this way. But using this little pattern you can forget about the tedious safety event raising checks and write like in the following line of code:

Updated(null, new AccountPositionEventArgs());

instead of:

EventHandler handler = Updated;
if (handler != null)
handler(null, new AccountPositionEventArgs());


I'll remember this great stuff.

Good luck!

No comments: