user2331443
user2331443

Reputation: 41

Is there any reason to define custom delegates?

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

Answers (3)

usr
usr

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

driis
driis

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:

  • When there are more than a few parameters, to improve readability and self-documentation.
  • If the name of the delegate could convey meaning to the user of an API
  • Perhaps for some P/Invoke operations, can't think of any right now.

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

Kenneth
Kenneth

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

Related Questions