Empty EventArgs January 24, 2014 posted in .net, c#, pro tip.

There is a small performance improvement you can make when invoking an event with new EventArgs. Usually, you have a code similar to this.

public event EventHandler<EventArgs> Clicked; protected virtual void OnClicked() { EventHandler<EventArgs> temp = Clicked; if (temp != null) temp(this, new EventArgs()); }

By the way, this invocation isn’t a 100% thread-safe and it might be theoretically JITted (but it won’t because it would cause lots of breaking changes since Microsoft originally promoted this pattern).

But back to the original idea, there is a static property EventArgs.Empty and you should use instead of the new object allocation. After that, the improved code looks like this.

public event EventHandler<EventArgs> Clicked; protected virtual void OnClicked() { EventHandler<EventArgs> temp = Clicked; if (temp != null) temp(this, EventArgs.Empty); }

You won’t get a massive improvement, but something is better than nothing and also I find this code easier to read.

Would you like to get top 5 links on C# every Monday?

Sign up to C# Digest and stay up to date!