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.
Example:
Output:
15
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:
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.
ShowSum oShowSum = delegate (int iEnd)
{
int iSum = 0;
for(int i=0; i <= iEnd; i++)
{
Console.WriteLine(i);
iSum += i;
}
return iSum; // Return a value from an anonymous method
};
result = oShowSum(3);
Console.WriteLine("Summation of 3 is " + result);
Console.WriteLine();
result = oShowSum(5);
Console.WriteLine("Summation of 5 is " + result);
}
}
Related Post: Delegates, Multicast Deletages (Multicasting)
Example:
//
Demonstrate an anonymous method
using system;
using system;
// Declare a
delegate type
delegate void
ShowSum();
class AnonymousMethod
{
static void 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);
}; // Notice the semicolon
}
}
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.
{
int iSum = 0;
for(int i=0; i <= iEnd; i++)
{
Console.WriteLine(i);
iSum += i;
}
return iSum; // Return a value from an anonymous method
};
result = oShowSum(3);
Console.WriteLine("Summation of 3 is " + result);
Console.WriteLine();
result = oShowSum(5);
Console.WriteLine("Summation of 5 is " + result);
}
}
Related Post: Delegates, Multicast Deletages (Multicasting)
No comments:
Post a Comment