C# program to call multiple methods from the delegate

Here, we are going to learn how to call multiple methods from the delegate in C#? By Nidhi Last updated : April 03, 2023

Problem statement

Here, we will create two methods and create the delegate to point the methods, delegates are just like a function pointer in C. we can invoke one or more than one method using delegates.

C# code to call multiple methods from the delegate

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().

C# Delegate Programs »






Comments and Discussions!

Load comments ↻






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