Monday, September 24, 2007
Event Add and Remove Overrides
In a previous post entitled "Events vs Delegates" I mentioned that events use delegates. I also said that the
Another way of thinking about an event, however, that it is really a specially kind of property that has
As an example, consider the code below in which
Note that
event keyword is basically an access modifier that prevents code outside the class from accessing anything other than the += and -= operators on the delegate.Another way of thinking about an event, however, that it is really a specially kind of property that has
add and remove accessors instead of the typical get and set accessors. The += is mapped to the add accessor and the -= is mapped to the remove accessor. If the accessors are omitted, the compiler just creates defaults and uses a delegate to store attached handlers. As an example, consider the code below in which
MyClass1 and MyClass2 essentially do the same thing. The compiler automatically creates default add and remove accessors for MyClass1, whereas they are explicitily declared for MyClass2.
public class MyClass1
{
public event EventHandler MyEvent;
}
public class MyClass2
{
private EventHandler _myEvent;
public event EventHandler MyEvent
{
add
{
_myEvent += value;
}
remove
{
_myEvent -= value;
}
}
}
Note that
MyClass2 creates a private delegate that is used by the accessors, so MyClass2 is equivalent to the defaults generated MyClass1. But, overriding the accessors provides a significant amount of power to the class that is exposing the events. For example, the overloaded accessors may be implemented to log when handlers are attached, store handlers in a structure other than a delegate, or even reject attaching a handler by throwing an exception if some state criteria is not met. The important thing is, however, that code using the overridden MyClass2.MyEvent attach to it with the += and -= just like it would attach to MyClass1.MyEvent.Subscribe to Posts [Atom]