Possible Duplicate:
What are the advantages of delegates?
I have created a sample application. I am really finding it difficult to understand why to use delegates because without delegates we can achieve everything .
class Program
{
public delegate double Integrand(double x);
static double MyFunc1(double x) { return x + 10; }
static double MyFunc2(double x) { return x + 20; }
public static double Gauss3DelMethod(Integrand f)
{
double a = f(1);
return a;
}
public static double Gauss3SimpleMethod(double x)
{
double a = x;
return a;
}
static void Main(string[] args)
{
//with delegates
double res = Gauss3DelMethod(MyFunc1);
double res1 = Gauss3DelMethod(MyFunc2);
//without delegates
double res2 = Gauss3SimpleMethod(MyFunc1(1));
double res3 = Gauss3SimpleMethod(MyFunc2(1));
int i = 0;
}
}
So, why should I use delegates?
In your particular example, maybe it’s not important. (It’s not clear what it’s trying to achieve.)
But suppose you wanted to make the method execute the same
MyFunc1orMyFunc2for several different inputs. For example, suppose you were implementing the Newton-Raphson method, to operate over a general function. In that situation, you couldn’t call the function once and pass that into the method – you want to pass the actual function into the method, so that the method can call it with whatever inputs it needs.A similar example is sorting. For example, using LINQ you can write something like:
There we’re passing a function to project each source element to the ordering key. We don’t have to execute that function ourselves –
OrderBywill do it for us (lazily).Of course, all of this can be done with single-method interfaces too – delegates and single-method interfaces have a lot in common. However, delegates have the following benefits over single-method interfaces:
All of these could have been addressed differently using single-method interfaces, of course, but delegates are a handy alternative.
In conclusion: delegates are very useful. Just because you’ve written some trivial code which doesn’t particularly require them doesn’t mean they’re not useful. I would strongly suggest you look into LINQ, event handlers and the TPL, all of which use delegates heavily.