Looking at the signatures for the Func and Converter delegates,
public delegate TResult Func<T, TResult>(T arg);
public delegate TOutput Converter<TInput, TOutput>(TInput input);
I'm struggling to see the difference between the two. Surely, if we rename the generic type arguments, they essentially amount to the same thing?
Can anyone explain why they both exist, please?
The Converter<TInput,TOutput> is a delegate to a method that converts an object to the target type.
An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. It can contain minimum 1 and maximum of 16 input parameters and does not contain any output parameter.
TResult. The type of the return value of the method that this delegate encapsulates. This type parameter is covariant. That is, you can use either the type you specified or any type that is more derived. For more information about covariance and contravariance, see Covariance and Contravariance in Generics.
The basic difference between Func and Action delegates is that while the former is used for delegates that return value, the latter can be used for those delegates in which you don't have any return value.
There is no difference. The reason for their existence is historical. Converter<T1,T2>
was already available in .NET 2.0, but a whole range of Func<>
delegate types were added later on. For consistency, Func<T,TResult>
was added, but it did the same thing as Converter<T1,T2>
.
There are lots of delegate types that are effictively the same - for example:
ThreadStart
MethodInvoker
Action
all have the same void Foo()
signature. Historically, the names were chosen by the specific use; but with LINQ and looking forwards, it seems clearer to focus on the signature - hence in .NET 3.5 they introduced things like Func<...>
and Action<...>
(families of delegates)
Unfortunately, they aren't really compatible at the variance level, so if you are using both you'll often have to shim between them. Which is a pain...
Converter<,>
was added in .NET 2.0. The various Func
s were added in 3.5 (I think). Now, sure, the framework designers could have said "Hey, we've already got a generic delegate for this", but it would have looked very odd to have all the other Func
s and not this one. And to avoid a breaking change Converter
must be left in place.
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