What is the difference between Action, Predicate and Func

Asked

Viewed 1,813 times

13

What’s the difference between Action, Predicate and Func in the C#?

I would like, if possible, examples of use.

1 answer

17


Func

Func is used to determine a delegate. That is to type (create a signature) an anonymous function. It specifies the types of various parameters and the type of the function return.

var operacoes = new Dictionary<string, Func<int, int, int>> {
    {"+", (op1, op2) => op1 + op2 },
    {"-", (op1, op2) => op1 - op2 },
    {"*", (op1, op2) => op1 * op2 },
    {"/", (op1, op2) => op1 / op2 }
};
Write(operacoes["+"](10, 20)); //imprime 30

I put in the Github for future reference.

in this case the function will have two integer parameters and its return will also be an integer.

Action

Action is a Func that will not have a return, ie, is anonymous function that returns nothing (would be the type void). She does an action instead of giving a result, as usually happens with functions.

var acoes = new Dictionary<string, Action<int>> {
    {"Criar", (parametro) => Criar(parametro) },
    {"Editar", (parametro) => Editar(parametro) },
    {"Apagar", (parametro) => Apagar(parametro) },
    {"Imprimir", (parametro) => Imprimir(parametro) }
};
acoes["Criar"](1); //executará o método Criar

I put in the Github for future reference.

The function will have an integer parameter.

Predicate

Predicate is a Func that returns a bool. Today he’s not much needed. Func solves well. Only use if you really want to indicate that it is not just any function, but a predicate (criteria for a filter). Predicate can only have one parameter. The two previous types allow up to 16 parameters since there are several types with different signatures.

var compareZero = new Dictionary<string, Predicate<int>> {
    {">", (x) => x > 0 },
    {"<", (x) => x < 0 },
    {"=", (x) => x == 0 }
};
Write(compareZero["="](5)); //imprimirá False

I put in the Github for future reference.

The examples are obviously simplified and without context.

They are especially useful with LINQ.

  • Perfect, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.