C# - Example of an array of delegates

Here, we are going to learn about the array of delegates and its C# implementation. By Nidhi Last updated : April 03, 2023

Array of Delegates Example in C#

Here, we will create three methods and create an array of delegates to point the methods, delegates are just like a function pointer in C. Then we call methods using an array of delegates.

C# program to demonstrate the example of an array of delegates

The source code to demonstrate the array of delegates is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate an array of delegates.

using System;

delegate void MyDel();

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

    static void Method2()
    {
        Console.WriteLine("\tMethod2 called");
    }

    static void Method3()
    {
        Console.WriteLine("\tMethod3 called");
    }

    static void Main()
    {
        MyDel[] del = new MyDel[3];


        del[0] = Method1;
        del[1] = Method2;
        del[2] = Method3;

        Console.WriteLine("Invoke methods using delegates:");
        for (int i = 0; i < 3; i++)
        {
            del[i]();
        }
    }
}

Output

Invoke methods using delegates:
        Method1 called
        Method2 called
        Method3 called
Press any key to continue . . .

Explanation

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

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

Console.WriteLine("Invoke methods using delegates:");
for (int i = 0; i < 3; i++)
{
    del[i]();
}

In the above code, we invoked the methods using an array of delegates using an index.

C# Delegate Programs »






Comments and Discussions!

Load comments ↻






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