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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

292 ❘ CHAPTER 12 Classes and Structures<br />

Raising Events<br />

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

catch the event. It does that by comparing the event to null. (This is a fairly odd syntax but that’s<br />

the way <strong>C#</strong> does it.)<br />

If the event handler isn’t null, the code “invokes” it, passing it any required parameters. The program<br />

then invokes each of the registered event handlers in turn, passing them those parameters.<br />

For example, suppose the Student class defined 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 />

Catching Events<br />

To subscribe to an event, a program uses the += operator to “add” the event handler to the event.<br />

For example, suppose the Person class defines a NameChanged event. Suppose the main program<br />

creates an instance of the Person class named MyPerson. Finally, suppose the main program defines<br />

an event handler named MyPerson_NameChanged to handle that event. Then the main program<br />

could use the following code to subscribe to the event.<br />

MyPerson.NameChanged += MyPerson_NameChanged;<br />

If the program executes this code multiple times, then when the event is raised, the event handler will<br />

be called multiple times.<br />

To unsubscribe from an event, use the -= operator. The following code shows how a program might<br />

unsubscribe from the Person class’s NameChanged event.<br />

MyPerson.NameChanged -= MyPerson_NameChanged;<br />

(This example is described further in the next section.)<br />

1 – 2 = 0<br />

A program can unsubscribe from an event more times than it subscribed to it without<br />

causing any harm. For example, if the program uses += to subscribe to the event three<br />

times and then uses -= to unsubscribe from it four times, nothing bad happens. The<br />

program just doesn’t catch the event.<br />

Using Event Delegate Types<br />

The delegate part of the event declaration is a delegate type that defines the parameters that the<br />

event handler takes when it catches the event. You can create your own delegate type, use a predefined<br />

Action delegate type, or use the special EventHandler delegate type.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!