Pages

Anonymous Methods

Anonymous
methods allow you to declare a method body without an explicit name.
They behave exactly like normal methods behind the scenes, however,
there is no way to explicitly call them in your code.

An
anonymous method is a block of code that is passed to a delegate. It
is created only to be used as a target for a delegate. The main
advantage to using an anonymous method is simplicity. It is a
preferred way for writing inline code.

You
can omit the parameter list in anonymous methods. Thus an anonymous
method can be converted to delegates with a variety of signatures,
which is not possible with lambda expressions.

Example:

//
Demonstrate an anonymous method

using
System;

//
Declare a delegate type

delegatevoidShowSum();

classAnonymousMethod

{

staticvoid
Main()

{

//
The code for generating the sum is passed as an anonymous method

ShowSum
oShowSum = delegate

{

//
This is the block of code passed to the delegate

int
iSum = 0;

for
(int
i = 0; i <= 5; i++)

{

iSum += i;

}

Console.WriteLine(iSum);

Console.ReadKey();

};
//
Notice the semicolon

oShowSum();

}

}

Output:
15

Pass
Arguments and Return a Value from an Anonymous Method

It is possible to pass one or more arguments to an anonymous method. To do so, follow the delegate keyword with a parenthesized parameter list. Then, pass the argument(s) to the delegate instance when it is called.

An anonymous method can also return a value. However, the type of the return value must be compatible with the return type specified by the delegate.

Example:

//
Demonstrate an anonymous method that returns a value.

using System;

//
This delegate returns a value. Notice that ShowSum now has a parameter.

delegate int ShowSum(int iEnd);class AnonymousMethod{ static void Main() { int result; //
Here, the ending value for the count is passed to the anonymous method. // A summation of the count is returned.