15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

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

194 ❘ ChaPTer 8 deleGAtes, lAmbdAs, And events<br />

To illustrate the use of multicast delegates, the following code recasts the SimpleDelegate example into<br />

a new example, MulticastDelegate. Because you now need the delegate to refer to methods that return<br />

void, you have to rewrite the methods in the MathOperations class, so they display their results instead of<br />

returning them:<br />

class MathOperations<br />

{<br />

public static void MultiplyByTwo(double value)<br />

{<br />

double result = value * 2;<br />

Console.WriteLine("Multiplying by 2: {0} gives {1}", value, result);<br />

}<br />

}<br />

public static void Square(double value)<br />

{<br />

double result = value * value;<br />

Console.WriteLine("Squaring: {0} gives {1}", value, result);<br />

}<br />

code snippet MulticastDelegates/MathOperations.cs<br />

To accommodate this change, you also have to rewrite ProcessAndDisplayNumber:<br />

static void ProcessAndDisplayNumber(Action action, double value)<br />

{<br />

Console.WriteLine();<br />

Console.WriteLine("ProcessAndDisplayNumber called with value = {0}", value);<br />

action(value);<br />

}<br />

Now you can try out your multicast delegate like this:<br />

static void Main()<br />

{<br />

Action operations = MathOperations.MultiplyByTwo;<br />

operations += MathOperations.Square;<br />

}<br />

ProcessAndDisplayNumber(operations, 2.0);<br />

ProcessAndDisplayNumber(operations, 7.94);<br />

ProcessAndDisplayNumber(operations, 1.414);<br />

Console.WriteLine();<br />

Now, each time ProcessAndDisplayNumber is called, it will display a message to say that it has been<br />

called. Then the following statement will cause each of the method calls in the action delegate instance to<br />

be called in succession:<br />

action(value);<br />

Running this code produces this result:<br />

MulticastDelegate<br />

ProcessAndDisplayNumber called with value = 2<br />

Multiplying by 2: 2 gives 4<br />

Squaring: 2 gives 4<br />

ProcessAndDisplayNumber called with value = 7.94<br />

Multiplying by 2: 7.94 gives 15.88<br />

Squaring: 7.94 gives 63.0436<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!