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.

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

Errors <strong>and</strong> exceptions are explained in detail in Chapter 15.<br />

In such a scenario, you can avoid the problem by iterating the list on your own. The Delegate class defi nes<br />

the method GetInvocationList() that returns an array of Delegate objects. You can now use this<br />

delegate to invoke the methods associated with them directly, catch exceptions, <strong>and</strong> continue with the<br />

next iteration:<br />

static void Main()<br />

{<br />

Action d1 = One;<br />

d1 += Two;<br />

}<br />

Delegate[] delegates = d1.GetInvocationList();<br />

foreach (Action d in delegates)<br />

{<br />

try<br />

{<br />

d();<br />

}<br />

catch (Exception)<br />

{<br />

Console.WriteLine("Exception caught");<br />

}<br />

}<br />

When you run the application with the code changes, you can see that the iteration continues with the next<br />

method after the exception is caught:<br />

One<br />

Exception caught<br />

Two<br />

anonymous methods<br />

Up to this point, a method must already exist for the delegate to work (that is, the delegate is defi ned<br />

with the same signature as the method(s) it will be used with). However, there is another way to use<br />

delegates — with anonymous methods. An anonymous method is a block of code that is used as the<br />

parameter for the delegate.<br />

The syntax for defi ning a delegate with an anonymous method doesn ’ t change. It ’ s when the delegate is<br />

instantiated that things change. The following is a very simple console application that shows how using an<br />

anonymous method can work:<br />

using System;<br />

namespace Wrox.ProCSharp.Delegates<br />

{<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

string mid = ", middle part,";<br />

Func < string, string > anonDel = delegate(string param)<br />

{<br />

param += mid;<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!