Definition of a delegate
A delegate (delegate) is a type that can store a reference as a function. This sounds pretty tricky, but the mechanics are very simple. A delegate's declaration is very similar to a function, but does not have a function body and uses the delegate keyword. The declaration of a delegate specifies a return type and a list of parameters.
After a delegate is defined, you can declare a variable of that delegate type. Initialize this variable directly to a function reference with the same return type and argument list as the delegate. After that, you can call the function with a delegate variable, just as the variable is a function.
After you have a variable that references a function, you can also perform an operation that cannot be done in any other way. For example, you can pass a delegate variable as an argument to a function so that the function can use the delegate to invoke any function that he references, and you don't need to know which function to call before you run it.
An example is given below:
Class Program
{
Delegate Double processdelegate (double param1,double param2);
Static double Multiply (double param1,double param2)
{
return param1*param2;
}
Static double Divide (double param1,double param2)
{
return param1/param2;
}
static void Main (string[] args)
{
Processdelegate process;
Console.WriteLine ("Enter 2 number separated with a comma:");
string input = Console.ReadLine ();
int commapos = input. IndexOf (', ');
Double param1 = convert.todouble (input. Substring (0,commapos));
Double param2 = convert.todouble (input. SubString (Commapos + 1,input.length-commapos-1));
Console.WriteLine ("Enter M to multiply or to divide:");
input = Console.ReadLine ();
if (input = = "M")
{
Process = new Processdelegate (Multiply);
}
Else
{
Process = new Processdelegate (Divide);
}
Console.WriteLine ("Result:{0}", Process (PARAM1,PARAM2));
Console.readkey ();
}
}
C # Learning Notes (Delegates)