Ross Coded Classes

Programming tips with no rose colored glasses.

Create Less Garbage with EventArgs.Empty

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

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; }
}