Reputation: 41
Except for the case of calling a method with lots of parameters (and perhaps supporting pre .NET 3.5 code), is there any justification for defining a custom delegate instead of just using Func and Action?
Upvotes: 2
Views: 82
Reputation: 171178
One aspect not mentioned so far is that Func
and Action
to not support ref
and out
parameters. Delegates can have them, though.
Upvotes: 2
Reputation: 164301
In modern C# code, you are right, it is seldomly required to create a custom delegate. For C#4, I would only create a custom delegate:
The reason why you tend to see some custom delegates in the .NET codebase is the fact that much of it was designed quite early, when C# was version 1 and had no anonymous delegates, lambdas, or generics. Therefore, a custom delegate was required for most operations that needed a delegate type.
Upvotes: 1
Reputation: 28737
In terms of functionality not really. In terms of readability the only thing I can imagine is to be more explicit. Consider the following example:
public delegate void MessageHandler(string msg);
// user custom delegate
public sub DoSomething(MessageHandler handler){}
// use generic action
public sub DoSomething(Action<string> handler){}
You can see here the first version is much more explicit because it exactly defines what is expected, therefore your client code will be more readable:
DoSomething(new MessageHandler(somefunc));
DoSomething(msg => ... );
Upvotes: 1