Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Func<T, TResult> delegate real world uses

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?

like image 546
Maxim Gershkovich Avatar asked Jun 01 '11 03:06

Maxim Gershkovich


3 Answers

If what you're asking, really, is why we have delegates in general:

  • If you've ever consumed an event, you've used a delegate
  • If you've ever used LINQ, you've used a delegate (technically, with an 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:

  1. People were having to declare their own simple delegate types when they needed a particular delegate in their code. While the 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.
  2. More importantly, the 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.
like image 91
Adam Robinson Avatar answered Sep 30 '22 09:09

Adam Robinson


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();
like image 31
Ry- Avatar answered Sep 30 '22 09:09

Ry-


I think a great example is lazy initialization.

var value = new Lazy<int>(() => ExpensiveOperation()); // Takes Func<T>
like image 29
ChaosPandion Avatar answered Sep 30 '22 07:09

ChaosPandion