C# - Implement Anonymous Method

Here, we are going to learn how to implement anonymous method using C# program?
Submitted by Nidhi, on September 10, 2020 [Last updated : March 22, 2023]

Anonymous Method

A method without a name is known as an anonymous method. Here, we defined an anonymous method, it is used to reduce the overhead of coding during the instantiation of delegate, because here it is not required to define a separate method.

C# program to implement anonymous method

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".

C# Basic Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.