What is Func<>
and what is it used for?
Think of it as a placeholder. It can be quite useful when you have code that follows a certain pattern but need not be tied to any particular functionality.
For example, consider the Enumerable.Select
extension method.
This method takes a Func<T, TResult>
instead of any concrete function. This allows it to be used in any context where the above pattern applies.
So for example, say I have a List<Person>
and I want just the name of every person in the list. I can do this:
var names = people.Select(p => p.Name);
Or say I want the age of every person:
var ages = people.Select(p => p.Age);
Right away, you can see how I was able to leverage the same code representing a pattern (with Select
) with two different functions (p => p.Name
and p => p.Age
).
The alternative would be to write a different version of Select
every time you wanted to scan a sequence for a different kind of value. So to achieve the same effect as above, I would need:
// Presumably, the code inside these two methods would look almost identical;
// the only difference would be the part that actually selects a value
// based on a Person.
var names = GetPersonNames(people);
var ages = GetPersonAges(people);
With a delegate acting as placeholder, I free myself from having to write out the same pattern over and over in cases like this.