Louis Rhys
Louis Rhys

Reputation: 35627

use Func<> (or Action<>) or create own delegate?

Which one is better in, say, parameter type in a method (not related to LINQ). Apparently Func is better since it's simpler, more descriptive, and if everyone is using this everything will become compatible (good). However I notice Microsoft uses its own delegate at some libraries, for example event handlers. So, what are the advantages and drawbacks of either of them? when should I use it?

Edits:

Upvotes: 12

Views: 1134

Answers (5)

Richard
Richard

Reputation: 108985

However I notice Microsoft uses its own delegate at some libraries, for example event handlers. So, what are the advantages and drawbacks of either of them? when should I use it?

Some of this is historic: APIs defined before C#3/.NET3 when Action<> and Func<> were added. For events EventHandler<T> is a better choice for events because it enforces the right convention.

Upvotes: 1

Tony Kh
Tony Kh

Reputation: 1572

Func<> and Action<> are preferable if they are actually appropriate in your case. Runtime creates instances of every type used in your program, and if you use Func once it means that the instance of type was created. In case of custom delegate things go in different way and new types will be created even though they are essentially similar to existing.

However sometimes custom delegates make code clearer.

Upvotes: 1

leppie
leppie

Reputation: 117220

They are for all purposes the same, except when the method has an Expression parameter. Those need to be defined as a 'lambda' and not delegate. This would be very problematic when dealing with IQueryable and getting the IEnumerable invoked/resolved instead (eg LINQ2SQL).

Upvotes: 1

TalentTuner
TalentTuner

Reputation: 17556

You can always create a class which holds the n number of input as class properties and pass the object of the class a single input in the func<> delegate

Upvotes: 0

user111013
user111013

Reputation:

Func<> is useful when it's very clear what they're used for, and the number of inputs is small.

When the number of inputs is larger, or there could be some ambiguity over the intent - then using a delegate with named arguments makes things clearer.

Upvotes: 5

Related Questions