15.02.2015 Views

C# 4 and .NET 4

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

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

D e l e g a t e s ❘ 193<br />

BubbleSorter.Sort(employees, Employee.CompareSalary);<br />

}<br />

}<br />

}<br />

foreach (var employee in employees)<br />

{<br />

Console.WriteLine(employee);<br />

}<br />

code snippet BubbleSorter/Program.cs<br />

Running this code shows that the Employees are correctly sorted according to salary:<br />

BubbleSorter<br />

Elmer Fudd, $10,000.00<br />

Bugs Bunny, $20,000.00<br />

Foghorn Leghorn, $23,000.00<br />

Daffy Duck, $25,000.00<br />

RoadRunner, $50,000.00<br />

Wile Coyote, $1,000,000.38<br />

multicast delegates<br />

So far, each of the delegates you have used wraps just one single method call. Calling the delegate amounts<br />

to calling that method. If you want to call more than one method, you need to make an explicit call through<br />

a delegate more than once. However, it is possible for a delegate to wrap more than one method. Such a<br />

delegate is known as a multicast delegate. If a multicast delegate is called, it will successively call each<br />

method in order. For this to make sense, the delegate signature should return a void ; otherwise, you would<br />

only get the result of the last method that is invoked by the delegate.<br />

With a void return type the Action < double > delegate can be used.<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

Action < double > operations = MathOperations.MultiplyByTwo;<br />

operations += MathOperations.Square;<br />

code snippet MulticastDelegates/Program.cs<br />

In the earlier example, you wanted to store references to two methods, so you instantiated an array of<br />

delegates. Here, you simply add both operations into the same multicast delegate. Multicast delegates<br />

recognize the operators + <strong>and</strong> += . Alternatively, you can also exp<strong>and</strong> the last two lines of the preceding<br />

code, as in this snippet:<br />

Action < double > operation1 = MathOperations.MultiplyByTwo;<br />

Action < double > operation2 = MathOperations.Square;<br />

Action < double > operations = operation1 + operation2;<br />

Multicast delegates also recognize the operators – <strong>and</strong> - = to remove method calls from the delegate.<br />

In terms of what ’ s going on under the hood, a multicast delegate is a class derived<br />

from System.MulticastDelegate , which in turn is derived from System.Delegate .<br />

System.MulticastDelegate , <strong>and</strong> has additional members to allow chaining of<br />

method calls together into a list.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!