Elisabeth Elisabeth - 5 months ago 21
C# Question

Creating delegates manually vs using Action/Func delegates

Today I was thinking about declaring this:

private delegate double ChangeListAction(string param1, int number);

but why not use this:

private Func<string, int, double> ChangeListAction;

or if
would have no return value I could use:

private Action<string,int> ChangeListAction;

so where is the advantage in declaring a delegate with the

Is it because of .NET 1.1, and with .NET 2.0 came
and with .NET 3.5 came


The advantage is clarity. By giving the type an explicit name it is more clear to the reader what it does.

It will also help you when you are writing the code. An error like this:

cannot convert from Func<string, int, double> to Func<string, int, int, double>

is less helpful than one which says:

cannot convert from CreateListAction to UpdateListAction

It also means that if you have two different delegates, both of which take the same types of parameters but conceptually do two entirely different things, the compiler can ensure that you can't accidentally use one where you meant the other.