C# program to demonstrate the example of anonymous method

Here, we are going to learn about the anonymous method and its C# implementation.
Submitted by Nidhi, on September 10, 2020

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.

Program:

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






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.