Func <T, TResult> delegates use of the real world

I recently played with a Func<T, TResult> delegate and created methods that return different instances of Func<T, TResult> containing lambda, but what I was trying my best to come up with was any good real ideas on why you need 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 beautiful and presents an interesting concept, I donโ€™t see what advantages such code provides.

So can anyone here provide any real examples where they had to use Func<T, TResult> , and in general why could this delegate be used?

+6
source share
8 answers

If you really ask why we have delegates in general:

  • If you have ever used an event, you have used a delegate
  • If you ever used LINQ, you used a delegate (technically, with an IQueryable provider you used an expression, but for LINQ-to-Objects you used a delegate)

Delegates provide a way to introduce your own behavior into another object. The most common use of events. The object provides an event, and you provide a function (anonymous or not) that is called when this event occurs.

If you ask why we have a delegate Func<T, TResult> (and similar), then there are two main reasons:

  • People had to declare their own simple delegate types when they needed a specific delegate in their code. Although Action<> and Func<> delegates cannot cover all cases, they are easy to provide and cover many cases when custom delegates are needed.
  • More importantly, the Func<T, TResult> delegate is widely used in LINQ-to-Objects to define predicates. More specifically, Func<T, bool> . This allows you to define a predicate that takes a strongly typed IEnumerable<T> element and returns a boolean using either a lambda or a regular function, and then passes that predicate to LINQ-to-Objects.
+11
source

You would use it in LINQ. So, for example, to double all the numbers in the list:

 myList.Select(x => x * 2); 

What a Func<TIn, TOut> . This is very useful when creating short code. A real-world example in one of the many tower defense games that 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(); 
+4
source

I think a great example is lazy initialization.

 var value = new Lazy<int>(() => ExpensiveOperation()); // Takes Func<T> 
+3
source

A canonical example of the need for a function pointer is that the comparison function goes to the sort subroutine. To have different sort keys, you create a lambda for the comparison function and pass it to the sort function.

Or for a simple example in the real world:

 IEnumerable<Person> FindByLastName(string lastName) { return Customers.Where(cust => cust.LastName == lastName); } 

In this example, cust => cust.LastName == lastName is not only a lambda, but it creates a closure by capturing the lastName parameter. In words, he creates a function that will be different each time FindByLastName called.

+3
source

The Func<T> delegate (and other overloads) gives you new ways to write abstractions in C #. To demonstrate some of the options, here are a few C # langauge constructs that can be written in place of delegates:

 Thread.Lock(obj, () => { // Safely access 'obj' here }); Enumerable.ForEach(collection, element => { // Process 'element' }); Exceptions.Try(() => { // Try block }).With((IOException e) => { // Handle IO exceptions }); 

They are quite primitive, so itโ€™s good to have a language construct for them. However, it demonstrates that Func and lambda expressions add a lot of expressive power. This allows you to write new constructs, such as a parallel loop (using .NET 4.0):

 Parallel.ForEach(collection, element => { // Process 'element' }); 
+2
source

First of all, Func<T> not a class, it is a delegate.

Basically, you can use it whenever you need a method argument or a delegate type property if you do not want to declare your delegate for this.

+1
source

The simple use of Funct<T> , besides being built into many frameworks such as LINQ, Mocking Tools, and Dependency Injection, should use it to create a factory-based delegate .

+1
source

Recently, I wanted an external program to call my method so that it could change the way it behaves.

My method alone simply converts the file from XLS to XML. But it was necessary to allow the calling code to specify, if necessary, an arbitrary number of transformations, which should be applied to each xls cell before writing as an xml tag. For example: convert separator "," to decimal separator to ".", Suppress thousands separator, etc. (Conversions were a replacement for all strings).

Then the callerโ€™s code simply had to add an arbitrary number of entries in the dictionary, where the key is a template and the value is a replacement string for this template. My method iterates over the dictionary and creates a new Func<string,string> for each entry. Then for each cell Func<string,string> are applied sequentially.

0
source

Source: https://habr.com/ru/post/889503/


All Articles