X hits on this document

1060 views

0 shares

0 downloads

0 comments

37 / 396

C# LANGUAGE SPECIFICATION

Within a class that declares an event member, the event behaves just like a field of a delegate type (provided the event is not abstract and does not declare accessors). The field stores a reference to a delegate that represents the event handlers that have been added to the event. If no event handles are present, the field is null.

The List class declares a single event member called Changed, which indicates that a new item has been added to the list. The Changed event is raised by the OnChanged virtual method, which first checks whether the event is null (meaning that no handlers are present). The notion of raising an event is precisely equivalent to invoking the delegate represented by the event—thus, there are no special language constructs for raising events.

Clients react to events through event handlers. Event handlers are attached using the += operator and removed using the -= operator. The following example attaches an event handler to the Changed event of a List.

using System;

class Test { static int changeCount;

static void ListChanged(object sender, EventArgs e) { changeCount++; }

static void Main() { List names = new List(); names.Changed += new EventHandler(ListChanged); names.Add("Liz"); names.Add("Martha"); names.Add("Beth"); Console.WriteLine(changeCount);// Outputs "3" } }

For advanced scenarios where control of the underlying storage of an event is desired, an event declaration can explicitly provide add and remove accessors, which are somewhat similar to the set accessor of a property.

1.6.6.5 Operators

An operator is a member that defines the meaning of applying a particular expression operator to instances of a class. Three kinds of operators can be defined: unary operators, binary operators, and conversion operators. All operators must be declared as public and static.

The List class declares two operators, operator == and operator !=, and thus gives new meaning to expressions that apply those operators to List instances. Specifically, the operators define equality of two List instances as comparing each of the contained objects using their Equals methods. The following example uses the == operator to compare two List instances.

using System;

24Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views1060
Page views1060
Page last viewedSat Dec 10 17:30:35 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments