Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I prefer Func<T, TResult> or Converter<TIn, TOut>?

Tags:

c#

.net

delegates

I'm writing a class with a type parameter T that accepts a delegate that converts the instance of T to a string. I could declare the type of such delegate as Func<T, string> or Converter<T, string>. Any reason I should prefer one or the other?

like image 492
Dan Stevens Avatar asked Jan 09 '14 14:01

Dan Stevens


People also ask

What is the use of Func delegate in c#?

We use Func<> to represent a method that returns something. If the function has parameters, the first generic argument(s) represent those parameters. The last generic argument indicates the return type. Func<int, DateTime, string> is a function with an int and DateTime parameter that returns a string .

How Func works in c#?

A Func in C# is a way to define a method in-line that has a return value. There is a similar concept of an Action that doesn't have a return value, but we'll get to that in a sec. The return value's type is always the last generic parameter on the Func 's definition.


2 Answers

The delegate definitions are identical in everything but name. Hence the only real value this could provide is preventing unnecessary allocations trying to convert from the input delegate type to the type you choose. In short if all of your input delegates are Func choosing Converter will cause you allocation overhead (and vice versa)

Overall though this is just a stylistic decision. I find the majority of new APIs are preferring to use Func and Action over other named delegates hence I would use that.

like image 134
JaredPar Avatar answered Sep 21 '22 10:09

JaredPar


I think you should use Converter because that's what your class requires: a converter.

You can, of course, use Func, but that Func would do the job of a Converter, so your intention is much clearer if you use Converter

like image 36
Øyvind Avatar answered Sep 24 '22 10:09

Øyvind