Getting to know anonymous methods
In the previous chapter, we already discussed how to declare a delegate using named methods. When using named methods, we've have to create a method first, give it a name, and then associate it with the delegate. To refresh our memory, a simple delegate declaration associated with a named method is provided as follows:
delegate void DelDelegate(int x); void DoSomething(int i) { /* Implementation */ } DelDelegate d = DoSomething;
From the preceding code, we simply create a delegate data type named DelDelegate
, and we also create a method named DoSomething
. After we have a named method, we can associate the delegate with the method. Fortunately, anonymous methods were announced in C# 2.0 to ease the use of delegates. They provide us with a shortcut to create a simple and short method that will be used once. The syntax to declare an anonymous method is as follows:
delegate([parameters]) { implementation }
The explanation for each element of the anonymous...