What are lambda expressions?
Lambda expressions are those of type A goes to B, meaning primarily a transformation. In C #, there are constant lambdas, and multiparametrized.
In C #, a lambda expression can be converted to:
- a
Delegate
: is a compiled method, which can be executed, and passed as if it were a variable for who needs it. Also called anonymous methods, because they do not have their own identifier.
- a
Expression<>
representing an expression tree that denote the transformation representing the lambda expression as a data structure.
Use in the form of Delegate
When converted to a delegate, lambda can be passed as if it were a variable. A lambda produces a delegate of a specific type that depends on the context in which it is created.
The calls below generate delegates of different types:
// delegate gerado do tipo Func<string, bool>
Func<string, bool> func = s => s == null;
// delegate gerado do tipo Predicate<string>
Predicate<string> pred = s => s == null;
So, each delegate of a different type can be passed as if it were a common variable, so you can call these methods like this:
pred("string to test");
All delegates, regardless of the specific type, inherit from the Delegate
class.
Closures on delegates
Lambdas can present in their content, variables present in the method that constructs it, imprisoning this variable, in the form of a reference to it. This is also possible when building inline delegates.
int i = 0;
Action incrementa = () => i++;
incrementa();
// neste ponto a variável i, terá seu valor incrementado
This is a very powerful tool, and also dangerous, especially when used in loops, using the value of the iteration variable.
var listFunc = new Func<int>[10];
for (int it = 0; it < 10; it++)
listFunc[it] = () => it;
// todos os elementos de listFunc retornam 10
// pois a variável it, neste ponto vale 10,
// e todos os delegates referenciam a mesma variável
Use in the form of Expression
When talking about lambda expression, it is common to get hit by this way of using them, but is widely used by frameworks such as EntityFramework
and MVC
, both from Microsoft.
LINQ supports the IQueryable
interface, which is based on the use of transformed lambdas in data structure, which it analyzes in order to create a query that can be executed in the database.
As these libraries do, you can read this data structure generated from a lambda expression, using the classes present in the System.Linq.Expressions .
In addition, these lambdas in the form of Expression
can be copied and modified, and then compiled, being one of the ways to generate dynamically executable code . You can also create a zero expression tree by dynamically generating integer methods by using the
29.01.2014 / 18:46