03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

776 ❘ Appendix K Classes and Structures<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

➤➤<br />

new—Hides an event with the same name defined in an ancestor class.<br />

virtual—If you mark an event as virtual, you can later replace it in a derived class<br />

by overriding it.<br />

override—If an ancestor class defines a virtual event, you can use the override<br />

keyword to override it.<br />

abstract—This keyword indicates the event is abstract, so derived classes must override<br />

the event to give it an implementation. As is the case with abstract methods, a<br />

class that contains an abstract event must be abstract and cannot be instantiated.<br />

sealed—This keyword indicates the event is no longer virtual, so it cannot be<br />

overridden in derived classes.<br />

static—This indicates the class itself raises the event rather than instances of the class.<br />

delegate—This is a delegate type that defines the parameters that will be passed to event<br />

handlers for the event.<br />

name—This is the name you want to give the event.<br />

To raise an event, first determine whether any other pieces of code have registered to receive the<br />

event by comparing the event to null. If code has registered to receive the event, invoke the event<br />

by name, passing it any necessary parameters.<br />

For example, suppose the Student class has a GradeChanged event. Then the following snippet<br />

inside the Student class raises the event, passing it the current Student object as a parameter.<br />

if (GradeChanged != null) GradeChanged(this);<br />

To subscribe to an event, use the += operator to “add” the event handler to the event. The following<br />

code shows how a program could register the MyPerson_NameChanged event handler to handle the<br />

MyPerson object’s NameChanged event.<br />

MyPerson.NameChanged += MyPerson_NameChanged;<br />

If you subscribe an event handler to an event multiple times, it executes multiple times when the<br />

event occurs.<br />

To unsubscribe from an event, use the -= operator, as in the following code.<br />

MyPerson.NameChanged -= MyPerson_NameChanged;<br />

Unsubscribing from an event more times than the event handler was originally registered does not<br />

throw an exception.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!