Q:

C# program to call multiple methods from the delegate

belongs to collection: C# Delegate Programs

0

C# program to call multiple methods from the delegate

All Answers

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

Program:

The source code to call multiple methods from delegates is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to call multiple methods from delegates.

using System;

delegate void MyDel();

class Sample
{ 
    static void Method1()
    {
        Console.WriteLine("\tMethod1 called");
    }

    static void Method2()
    {
        Console.WriteLine("\tMethod2 called");
    }
 
    static void Main()
    {
        MyDel del1, del2, del3, del4;

        del1 = Method1;
        del2 = Method2;

        del3 = del1 + del2;
        del4 = del3 - del1;

        Console.WriteLine("Invoke del1:");
        del1();

        Console.WriteLine("Invoke del2:");
        del2();

        Console.WriteLine("Invoke del3:");
        del3();

        Console.WriteLine("Invoke del4:");
        del4();
    }
}

Output:

Invoke del1:
        Method1 called
Invoke del2:
        Method2 called
Invoke del3:
        Method1 called
        Method2 called
Invoke del4:
        Method2 called
Press any key to continue . . .

Explanation:

In the above program, we created a Sample class that contains three static methods Method1() and Method2(), and Main().

Method1() and Method2() are used to print a message on the console screen. In the Main() method we bind the methods with delegates.

In the above code, delegate del3 combine delegate del1 and del2. The delegate del3 will call method Method1() and Method2(). In the del4, we removed del1 from del3 then it will call only Method2().

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

total answers (1)

C# program to demonstrate the example of an array ... >>
<< C# program to declare and instantiate delegate...