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.
Program:
The source code to demonstrate the array of delegates is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
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.
In the above code, we invoked the methods using an array of delegates using an index.
need an explanation for this answer? contact us directly to get an explanation for this answer