What is Anonymous methods ?How to use Delegate keyword?
Anonymous method is a method which is introduced in C# from 3.0 and higher version. This method uses delegate keyword to pass a block of code. By using this methods, we can reduce the coding overhead in instantiating delegates because we do not have to create a separate method. Creating anonymous methods is a way to pass a code block as a delegate parameter.
An anonymous method is an inline method . It does not have a name.
Syntax for Anonymous method is given below:
// Create a delegate.
delegate void Del(int x);
// Instantiate the delegate using an anonymous method.
Del d = delegate(int y) { /* ..... */ };
Example of Anonymous method:
using System;
namespace Anonymous_Methods
{
class Anonymous
{
delegate int Del(int l, int b); //Anonymous method is created using delegate keyword.
static void Main(string[] args)
{
new Anonymous().Subtraction();
new Anonymous().Multiplication();
new Anonymous().Addition();
}
public void Subtraction()
{
Del sub = delegate (int length, int breadth)
{
return length - breadth;
};
Console.WriteLine("Subtraction is:");
Console.WriteLine(sub.Invoke(10, 5).ToString());
}
public void Addition()
{
Del add = delegate (int length, int breadth)
{
return length + breadth;
};
Console.WriteLine("Addition is:");
Console.WriteLine(add.Invoke(7, 4).ToString());
}
public void Multiplication()
{
Del A = delegate (int length, int breadth)
{
return length * breadth;
};
Console.WriteLine("Area of rectangle is:");
Console.WriteLine(A.Invoke(5, 6).ToString());
}
}
}
Output of the above program is shown below.
Also read : What is TempData? How to store object in TempData?