I've recently been playing around with the delegate Func<T, TResult>
and creating methods that return different instances Func<T, TResult>
containing lambda but what I have struggled to come up with is any good real world ideas of why one might want to return (or even create such an instance).
There is an example on MSDN where they do the following...
Func<string, string> convertMethod = UppercaseString;
private static string UppercaseString(string inputString)
{
return inputString.ToUpper();
}
And although it looks pretty and is an interesting concept I fail to see what advantages such code provides.
So could someone here please provide any real world examples where they have had to use Func<T, TResult>
and in general why one might want to use this delegate?
If what you're asking, really, is why we have delegates in general:
IQueryable
provider you've used an expression, but for LINQ-to-Objects you've used a delegate)Delegates provide a way of injecting your own behavior into another object. The most common usage is with events. An object exposes an event and you provide a function (anonymous or not) that gets called when that event fires.
If you're asking why we have the Func<T, TResult>
(and similar) delegate, then there are two main reasons:
Action<>
and Func<>
delegates can't cover all cases, they are simple to provide and cover many of the cases where custom delegates were needed.Func<T, TResult>
delegate is used extensively in LINQ-to-Objects to define predicates. More specifically, Func<T, bool>
. This allows you to define a predicate that takes a strongly-typed member of an IEnumerable<T>
and returns a boolean by using either a lambda or ordinary function, then pass that predicate to LINQ-to-Objects.You would use it a lot in LINQ. So, for example, to double all the numbers in a list:
myList.Select(x => x * 2);
That's a Func<TIn, TOut>
. It's quite useful when creating concise code. A real-world example is in one of the many tower-defence games I made, I calculated the closest enemy to the tower using one line:
enemies.Select(x => tower.Location.DistanceTo(x.Location)).OrderBy(x => x).FirstOrDefault();
I think a great example is lazy initialization.
var value = new Lazy<int>(() => ExpensiveOperation()); // Takes Func<T>
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