What's the difference between Action
, Predicate
and Func
in C #?
I would like examples of use if possible.
What's the difference between Action
, Predicate
and Func
in C #?
I would like examples of use if possible.
Func
Func
is used to determine a delegate
. In other words, it is to type (create a signature) an anonymous function. It specifies the types of several parameters and the return type of the function.
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
In this case the function will have two integer parameters and its return will also be an integer.
Action
Action
is a Func
that does not it will have a return, that is, it is anonymous function that returns nothing (it would be type void
). It 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
The function will have an integer parameter.
Predicate
Predicate
is a Func
that returns a bool
. Today it is not very necessary. Func
resolves fine. Only use if you really want to indicate that this is not some function, but rather a predicate (criterion 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
The examples are obviously simplified and context-free.
They are especially useful with LINQ.