13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>C#</strong> LANGUAGE SPECIFICATION}void CancelButtonClick(object sender, EventArgs e) {// Handle CancelButton.Click event}Here, the LoginDialog instance constructor creates two Button instances and attaches event handlers to theClick events. end example]17.7.1 Field-like eventsWithin the program text of the class or struct that contains the declaration of an event, certain events can be usedlike fields. To be used in this way, an event must not be abstract or extern, and must not explicitly includeevent-accessor-declarations. Such an event can be used in any context that permits a field. The field contains adelegate (§22), which refers to the list of event handlers that have been added to the event. If no event handlershave been added, the field contains null.[Example: In the examplepublic 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;}Click is used as a field within the Button class. As the example demonstrates, the field can be examined,modified, and used in delegate invocation expressions. The OnClick method in the Button class “raises” theClick event. The notion of raising an event is precisely equivalent to invoking the delegate represented by theevent—thus, there are no special language constructs for raising events. Note that the delegate invocation ispreceded by a check that ensures the delegate is non-null.Outside the declaration of the Button class, the Click member can only be used on the left-hand side of the +=and –= operators, as inb.Click += new EventHandler(…);which appends a delegate to the invocation list of the Click event, andb.Click –= new EventHandler(…);which removes a delegate from the invocation list of the Click event. end example]When compiling a field-like event, the compiler automatically creates storage to hold the delegate, and createsaccessors for the event that add or remove event handlers to the delegate field. In order to be thread-safe, theaddition or removal operations are done while holding the lock (§15.12) on the containing object for an instanceevent, or the type object (§14.5.11) for a static event.[Note: Thus, an instance event declaration of the form:class X{public event D Ev;}could be compiled to something equivalent to:class X{private D __Ev; // field to hold the delegate248

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!