How useful is FuncT, TResult

6

I was researching a few things and came across Func<T, TResult> , and I did not quite understand the utility of it.

For example:

//Método
public string Nome(string nome)
{
    return "Meu nome é " + nome
}

//Ao utiliza-lo eu chamaria assim
string nome = Nome("Josias");

And using Func<T, TResult> :

Func<string, string> metodo = Nome;

string nome = metodo("Josias");

I could not see any difference in using Func<T, TResult> .

In what cases would it be useful to use Func<T, TResult> ?

    
asked by anonymous 11.06.2015 / 21:15

3 answers

6

How useful

Passing a function (or function) to another function. It's a type of delegate .

How to read Func<T, TResult>

  

Function with an argument of type T that returns a value of type TResult .

I could not notice any difference in using Func<T, TResult> .

Actually you have not passed any function for a variable used in another function. Just called the variable with the argument. That is why utility is not well understood.

In what cases would it be useful to use Func<T, TResult> ?

dcastro's answer has a good example . I'll put another based on his:

IEnumerable<int> AplicarOperacaoMatematicaEmLista(IEnumerable<int> lista, Func<int, int> funcao)
{
    foreach (var item in lista)
        yield return funcao(item);
}

Usage:

var potenciaDeDois = delegate(int numero) { return numero * numero; };
var listaDeInteiros = new List<int> { 2, 4, 6, 8, 10 };
var listaDeQuadrados = AplicarOperacaoMatematicaEmLista(listaDeInteiros, potenciaDeDois);
// Vai imprimir uma lista com { 4, 16, 36, 64, 100 }
    
12.06.2015 / 00:12
8

Imagine you are writing a method that transforms each element of a list into another element. You want this transformation to be arbitrary, and defined by the user. This would be implemented like this:

IEnumerable<TResult> Map<T, TResult>(IEnumerable<T> collection, Func<T, TResult> transform)
{
    foreach(var item in collection)
        yield return transform(item);
}

Thus, the user can pass as argument any function that receives one of the elements of the list (of type T ) as argument and that turns it into another element (of type TResult ).

var list = new List<int> {1,2,3};
var doubled = Map(list, item => item * 2);

Moral of the story: Func<T, TResult> (and any other delegate in general) serves to pass arbitrary functions. It serves to treat functions as objects / values (this is the pillar of the FP - functional programming paradigm).

This method I used as an example ( Map ) is actually identical to the Enumerable.Select ". In fact, LINQ extensions depend heavily on passing delegates as arguments ( Where , Any , All , GroupBy , OrderBy , SelectMany , SkipWhile , etc).     

11.06.2015 / 23:48
1

Func is a delegate (a "pointer" to a function).

In this case, any method that receives a string as a parameter and return a string can be used.

Take the time to study Action and Predicate as well:

link

    
11.06.2015 / 22:21