I recently just started looking at Func
in C#, and as far as I can tell, they pretty much are the same as methods, which is fair enough. However, I was wondering if there is any point in using them, because as far as I can tell they seem to just be a slightly less version of methods. Consider the following:
Func<int,int> SquareTheNumber = x => { return x * x };
public int ReturnTheSquare (int x)
{
return x * x;
}
So is there any instance where a Func
should be used over a method?
4
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.
2
I recently just started looking at
Func
in C#, and as far as I can tell, they pretty much are the same as methods, which is fair enough.
Func
s (and Action
s) are objects. Methods aren’t.
In an object-oriented language, where everything you do is done by manipulating, constructing, passing, returning, and storing objects, something not being an object is an extremely severe restriction. So, no, they are not “pretty much the same”, they are in fact fundamentally different. In some sense, they could not be more different.
- You can pass a
Func
as an argument. You can’t do that with a method, because you can only pass objects as arguments and methods aren’t objects. - You can return a
Func
. You can’t do that with a method, because you can only return objects and methods aren’t objects. - You can assign a
Func
to a variable. You can’t do that with a method, because you can only assign objects to variables and methods aren’t objects. - You can construct a
Func
at runtime. You can’t do that with a method.
4