A delegate is a reference type that points to a method. This is how MSDN documentation describes a delegate:
"Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value."
Take a look at this delegate:
public delegate int SumPtr(int x,int y);
Let's make a method that could be called by the delegate:
int Add(int x,int y)
{
return x+y;
}
This is how we use a delegate to call this method:
SumPtr sPtr=new SumPtr(Add);
Console.WriteLine(sPtr(34,6));//prints 40
In .NET 2.0 we can also use an annonymous method with a delegate:
SumPtr sPtr2 = delegate(int x,int y)
{
return x+y;
}
.method private hidebysig static int32 '<.ctor>b__0'(int32 x, int32 y) cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) //
Let's consider a problem of calculating a numerical integral. We would like to have a method which takes different functions and outputs corresponding values of the integral of these functions. In C++ the code would look like this:
The method integral takes a delegate instead of a pointer to a function. An instance of a delegate new Integral.Function(f1) must be passed to the method integral.
using System;
//calculate the integral of f(x) between x=a and x=b by splitting the interval in step_number steps
class Integral
{
public delegate double Function(double x);
//declare a delegate that takes a double and returns a double
public static double
integral(Function f,double a, double b,int step_number)
{
double sum=0;
double step_size=(b-a)/step_number;
for(int i=1;i<=step_number;i++)
sum=sum+f(a+i*step_size)*step_size;
//divide the area under f(x) into step_number rectangles and sum their areas
return sum;
}
}
class Test
{
//simple functions to be integrated
public static double f1(
double x)
{
return x*x;
}
public static double f2(double x)
{
return x*x*x;
}
public static void Main()
{//output the value of the integral.
Console.WriteLine(Integral.integral(new Integral.Function(f1),1,10,20));
Console.WriteLine(Integral.integral(new Integral.Function(f2),1,10,20));
}
}