Internals events: In.net as events presented internally?
If you type this:
public event EventHandler MyEvent;
what the compiler generates is (simplified):
// declares a normal delegate of type 'EventHandler'
private EventHandler _myEvent;
// declares 'add_MyEvent' and 'remove_MyEvent' methods similar to a property
public event EventHandler MyEvent {
add { _myEvent += value; }
remove { _myEvent -= value; }
}
An event is like a property; a wrapper around the delegate that allows you to add or remove methods. This means that you cannot completely reassign a delegate and remove other subscribers to it.
Everything you do when specifying events in the interface, is that for all the implementation classes should be the methods add
and remove
for the event. Much like declaring a property on an interface, in fact.
Also, you can only call or re-assign the event in the class in which it is declared - any references to the event MyEvent
inside the class are redirected to use the delegate directly, whereas outside the class you can only access the methods add
and remove
, not the delegate directly.
a source to share
@thecoop's answer is a very good description of "field events" (noting the "simplified" disclaimer), but note that in fact events can be implemented in any way you like . The whole event defines a pair of add
/ accessories remove
(so it can be defined on an interface like a property).
For example, for rare events, the following may be common:
private static readonly object FooKey = new object(), BarKey = new object();
public event EventHandler Foo {
add {Events.AddHandler(FooKey, value);}
remove {Events.RemoveHandler(FooKey, value);}
}
public event MouseClickEventHandler Bar {
add {Events.AddHandler(BarKey, value);}
remove {Events.RemoveHandler(BarKey, value);}
}
where Events
is EventHandlerList
, usually with a delay:
private EventHandlerList events;
protected EventHandlerList Events {
get {
if(events == null) events = new EventHandlerList();
return events;
}
}
Or you could do something else that you like. Within reason (noting the expected behavior of event subscription and equality / composite delegate delegation).
a source to share