A delegate is a type that refers to a static method or an instance method, and then used to call this method.
Following code explains how to create and use a delegate.
Steps involved are
1)Define the delegate type to specify its signature.
2)Declaring the Delegate Variable
3)Initializing the Delegate Variable with reference to any function
4)Calling the function
public class Program { //Defining the Delegate type public delegate double ProcessDelegate(int param1, int param2); public static double Multiply(int param1, int param2) { return param1 * param2; } public static double Divide(int param1, int param2) { return param1 / param2; } public static void Main(string[] args) {
public static void Main(string[] args) { //Declaring the Delegate Variable ProcessDelegate processDelegate; //Initializing Delegate Variable with reference to Multiply function processDelegate = new ProcessDelegate(Multiply); double result; result = processDelegate(6, 3); // Calling the Delegate Console.WriteLine(result); //Initializing the Delegate Variable with reference to Divide function processDelegate = new ProcessDelegate(Divide); result = processDelegate(6, 3); // Calling the Delegate Console.WriteLine(result); //Initializing the Delegate Variable with reference to Sum function Addition testClass = new Addition(); processDelegate = new ProcessDelegate(testClass.Sum); result = processDelegate(6, 3); // Calling the Delegate Console.WriteLine(result); Console.ReadKey(); }
}
public class Addition
{
public double Sum(int a, int b)
{
return a + b;
}
}
Note:- Signature of the delegate and function should match for a delegate to refer to a function