I understood Func, Action, Predicate with the help of some amazing posts available on this site and in short-
Action
is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Func
is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
Predicate
is a special kind of Func
often used for comparisons.
Now I'm confused in Converter
and Comparison
delegate,why .Net Framework introduced these 2 delegate flavours for just converting and comparing, when and how to use these 2 over existing 3.
Please provide simpler and shorter example for understanding.
Now I'm confused in Converter and Comparison delegate,why .Net Framework introduced these 2 delegate flavours for just converting and comparing, when and how to use these 2 over existing 3.
Historically, the delegates were introduced in the opposite order to the order your question suggests.
Predicate<T>
, Converter<TInput, TOutput>
and Comparison<T>
were introduced in .NET 2.0. They were used by List<T>
and a few other types. At this point in time C# didn't support lambda expressions but did support anonymous methods. Delegates were mostly used for event handling and starting threads... supporting them for predicates, conversion and comparison was a baby step, effectively.
Note that Predicate<T>
isn't used for comparisons - it's used for testing a single value. For example, you could have a Predicate<string>
for "Is the string length more than 5 characters?" Comparison<T>
, however, is for comparing values - it's used for sorting.
The Func
and Action
delegates were (mostly - Action<T>
was in .NET 2.0; used by List<T>.ForEach
) introduced in .NET 3.5, with LINQ. That was the time frame in which C# 3 introduced lambda expressions and its LINQ support as well, and suddenly delegates were everywhere. I believe the level of awareness of delegates (and how they could be used) went up massively with C# 3.
Early pre-releases of LINQ used Predicate<T>
instead of Func<T, bool>
, but then additional overloads of Where
were introduced accepting Func<T, int, bool>
to allow the index to be part of the predicate.
I suspect that if the framework were redesigned from scratch, the "special purpose" delegates (Predicate<T>
, Converter<TInput, TOutput>
and Comparison<T>
) might not exist. It's possible that Predicate<T>
and Comparison<T>
would still exist, as they provide additional semantic hints as to the purpose of the delegate which can help readability - but Converter<TInput, TOutput>
really doesn't have any benefits over Func<T, TResult>
.
See more on this question at Stackoverflow