Explain how to implement Delegates in C#.NET
Here is an implementation of a very simple delegate that accepts no parameters.
public delegate void MyDelegate();// Declaration
class MyClass
{
public static void MyFunc()
{
Console.WriteLine("MyFunc Called from a Delegate");
}
public static void Main()
{
MyDelegate myDel = new MyDelegate(MyFunc);
myDel();
}
}
namespace Delegates
{
public delegate int DelegateToMethod(int x, int y);
public class Math
{
public static int Add(int a, int b)
{
return a + b;
}
public static int Multiply(int a, int b)
{
return a * b;
}
public static int Divide(int a, int b)
{
return a / b;
}
}
public class DelegateApp
{
public static void Main()
{
DelegateToMethod aDelegate = new DelegateToMethod(Math.Add);
DelegateToMethod mDelegate = new DelegateToMethod(Math.Multiply);
DelegateToMethod mDelegate = new DelegateToMethod(Math.Multiply);
DelegateToMethod dDelegate = new DelegateToMethod(Math.Divide);
Console.WriteLine("Calling the method Math.Add() through the aDelegate object");
Console.WriteLine(aDelegate(5, 5));
Console.WriteLine("Calling the method Math.Multiply() through the mDelegate object");
Console.WriteLine(mDelegate(5, 5));
Console.WriteLine("Calling the method Math.Divide() through the dDelegate object");
Console.WriteLine(dDelegate(5, 5));
Console.ReadLine();
}
}
}