Ross Coded Classes

April 7, 2007

Create Less Garbage with EventArgs.Empty

Filed under: .NET Tips — Tags: , — Ross Bradbury @ 6:20 pm
Create less garbage in memory by using EventArgs.Empty instead of new EventArgs().  There are other framework classes that have similar static methods, like StringComparer.InvariantCultureIgnoreCase.
 
Whenever you need to pass an EventArgs instance to something, don’t construct a new EventArgs().  Instead, use EventArgs.Empty.  I have observed certain actions in previous releases of Infragistics UltraGrid that created several hundred thousand EventArgs objects per second, adding stress to the garbage collector.

Event Properties

Filed under: .NET Tips — Tags: , — Ross Bradbury @ 6:00 pm

Don’t forget about event properties.

Sometimes an interface requires an event that really is the same as an existing event.  This can be accomplished by forwarding the new to the existing event. 

There is nothing wrong with this version:

public event EventHandler ValueChanged;

protected override void OnCheckedValueChanged()
{
      base.OnCheckedValueChanged();

      EventHandler handler = ValueChanged;
      if handler != null)
      {
            handler(this, EventArgs.Empty);
      }
}

This does the same thing and I think this version is cleaner:

public event EventHandler ValueChanged
{
      add { CheckedChanged += value; }
      remove { CheckedChanged -= value; }
}

Create a free website or blog at WordPress.com.