Wednesday, June 4, 2008

Empty EventArgs

How many times have you written an event whose event handler just takes in a generic EventArgs object and when you raise that event you pass in new EventArgs()?  Turns out the EventArgs class has a static read-only instance field EventArgs.Empty that you can use so you don't have to instantiate a new copy of this class for no reason.  Microsoft's documentation says that this instance is the equivalent of calling the constructor.  Again the benefit is that this instance is already created.

To quote a colleague, "Think of the performance boost we’ll get!"  I'm fairly certain he was being sarcastic.

public event EventHandler<EventArgs> MyEvent;

protected void OnMyEvent(EventArgs e)
{
	EventHandler<EventArgs> hnd = MyEvent;
	if (hnd != null) hnd(this, e);
}

public void DoSomething()
{
	OnMyEvent(EventArgs.Empty);
}

Technorati Tags:

Submit this story to DotNetKicks

1 comments:

SuperJason said...

I'm never sarcastic!