Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer.
Declaration
public delegate double Delegate_Prod(int a,int b);
class Class1
{
static double fn_Prodvalues(int val1,int val2)
{
return val1*val2;
}
static void Main(string[] args)
{
//Creating the Delegate Instance
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
Console.Write("Please Enter Values");
int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());
//use a delegate for processing
double res = delObj(v1,v2);
Console.WriteLine ("Result :"+res);
Console.ReadLine();
}
}
Explanation
Here I have used a small program which demonstrates the use of delegate.
The delegate "Delegate_Prod
" is declared with double return type and accepts only two integer parameters.
Inside the class, the method named fn_Prodvalues
is defined with double return type and two integer parameters. (The delegate and method have the same signature and parameter type.)
Inside the Main
method, the delegate instance is created and the function name is passed to the delegate instance as follows:
Collapse | Copy Code
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
After this, we are accepting the two values from the user and passing those values to the delegate as we do using method:
Collapse | Copy Code
delObj(v1,v2);
Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.