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?
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With