Sunstorm Labs Blog

October 15, 2008

C# events are actually accessors

Filed under: C# — Tags: , , — admin @ 1:00 pm

An interesting feature of C# I discovered recently is that events are actually accessors into Multicast Delegates, much like properties are accessors into other fields.

private string myData;
public string MyData // A property
{
  get { return myData; } // called when the property is read
  set { myData = value; } // called when the property is written to
}
 
private EventHandler myDataChanged;
public event EventHandler MyDataChanged // An event
{
  add { myDataChanged = (EventHandler)Delegate.Combine( myDataChanged, value ); } // called when a handler is attached
  remove { myDataChanged = (EventHandler)Delegate.Remove( myDataChanged, value ); } // called when a handler is detached
}

(more…)

Powered by WordPress