The source code to demonstrate the anonymous method is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# Program to demonstrate the anonymous method.
using System;
delegate void MyDel(int n1, int n2);
class Sample
{
static void Main()
{
MyDel M = delegate(int n1, int n2)
{
Console.WriteLine("Sum: "+(n1+n2));
};
M(5,2);
M = new MyDel(TestClass.Multiply);
M(5,2);
}
static void Multiply(int n1, int n2)
{
Console.WriteLine("Multiply: " + (n1 * n2));
}
}
Output:
Sum: 7
Multiply: 10
Press any key to continue . . .
Explanation:
In the above program, we created a Sample class that contains two static methods Main() and Multiply().
delegate void MyDel(int n1, int n2);
Here we defined a delegate MyDel, the delegate is similar to the function pointer in C. It is initialized with the name of the method, and then we can call the method using a delegate.
MyDel M = delegate(int n1, int n2)
{
Console.WriteLine("Sum: "+(n1+n2));
};
Here we defined an anonymous method and initialized with delegate instance "M" and then we called the method using instance "M".
M = new MyDel(TestClass.Multiply);
M(5,2);
In the above code, we re-instantiate the "M" with the method "Multiply" and then call the multiply method using delegate "M".
Program:
The source code to demonstrate the anonymous method is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a Sample class that contains two static methods Main() and Multiply().
Here we defined a delegate MyDel, the delegate is similar to the function pointer in C. It is initialized with the name of the method, and then we can call the method using a delegate.
Here we defined an anonymous method and initialized with delegate instance "M" and then we called the method using instance "M".
In the above code, we re-instantiate the "M" with the method "Multiply" and then call the multiply method using delegate "M".