ECMA-334 C# Language Specification17.7.1: Field-like events |
Within the program text of the class or struct that contains the declaration of an event, certain events can be used like fields. To be used in this way, an event must not be abstract or extern, and must not explicitly include event-accessor-declarations
. Such an event can be used in any context that permits a field. The field contains a delegate (22), which refers to the list of event handlers that have been added to the event. If no event handlers have been added, the field contains null.
public delegate void EventHandler(object sender, EventArgs e);
public class Button: Control
{
public event EventHandler Click;
protected void OnClick(EventArgs e) {
if (Click != null) Click(this, e);
}
public void Reset() {
Click = null;
}
}
which appends a delegate to the invocation list of the Click event, and
b.Click += new EventHandler(...);
which removes a delegate from the invocation list of the Click event. end example]
b.Click -= new EventHandler(...);
When compiling a field-like event, the compiler automatically creates storage to hold the delegate, and creates accessors for the event that add or remove event handlers to the delegate field. In order to be thread-safe, the addition or removal operations are done while holding the lock (15.12) on the containing object for an instance event, or the type object (14.5.11) for a static event.
could be compiled to something equivalent to:
class X {
public event D Ev;
}
class X {
private D __Ev; // field to hold the delegate
public event D Ev {
add {
lock(this) { __Ev = __Ev + value; }
}
remove {
lock(this) { __Ev = __Ev - value; }
}
}
}
could be compiled to something equivalent to:
class X {
public static event D Ev;
}
end note]
class X {
private static D __Ev; // field to hold the delegate
public static event D Ev {
add {
lock(typeof(X)) { __Ev = __Ev + value; }
}
remove {
lock(typeof(X)) { __Ev = __Ev - value; }
}
}
}