Q:

C# program to demonstrate the example of anonymous method

0

C# program to demonstrate the example of anonymous method

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | Class, Object, Methods

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to create an obsolete method in a class... >>
<< C# program to demonstrate the concept of method hi...