A Func
is just a special kind of (well a family of, really) delegate. Naturally, C# would be turing-complete even without them, so of course nobody "needs" them, it's just that they make a lot of things A LOT simpler design- and syntax-wise.
They take on a similar role to function pointers in languages like C. It's basically a way for you to decouple yourself from a specific method, and instead depend on a polymorphic class ("class" in a non-OOP sense) of methods.
One pretty simple example when they are useful is the map
method in the IEnumerable<T>
functor (named Select
in C#):
public static IEnumerable<TResult> Select<T, TResult>(this IEnumerable<T> xs, Func<T, TResult> f)
{
foreach (var x in xs) yield return f(x);
}
This can now be called via new[] {1,2,3}.Select(x => x*2)
instead of defining som one-method interface and creating a whole class just for multiplying a number by 2.
Explicitly naming and placing each small lambda in a class in a namespace would just bloat things and add no clarity.
this
which refer to the instance of the current object. This is the main difference in every language between function and method. Note that a static method don't have a this since the goal of static method is to be used without having instanting the class