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#?
Submitted by Nidhi, on September 15, 2020

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.

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

C# Delegate Programs »


ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




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.