Lambda Expressions By Val Feldsher
Used to create delegates or expression tree types Overview Anonymous function Lambda Expressions Expression Lambda Statement Lambda Used to create delegates or expression tree types May or may not have parameters Implicit Explicit Operator => (goes to) (input parameter) => statement/expression
Lambdas are less verbose than anonymous methods Anonymous: Lambda vs. Anonymous Lambdas are less verbose than anonymous methods Anonymous: Lambda
Simple expression on right hand side x => 2 * x (x, y) => x + y Expression Lambdas Simple expression on right hand side x => 2 * x Simple expression, no brackets necessary (x, y) => x + y Need prentices if specifying more than one parameter. (int x, string y) => y.Length > x Sometimes types need to be specified explicitly because they can’t be inferred. () => MyFunction() No parameters
Lambdas can contain multi-line statements on the right hand side Statement Lambdas Lambdas can contain multi-line statements on the right hand side
Standard Query Operators Many standard query operators (LINQ) take a generic delegate of type Func<T, Tresult> as a parameter.
Type can be inferred from: Type Inference Type can be inferred from: Underlying delegate Type of elements in source sequence(LINQ) General rules: Must contain same number of parameters as delegate Each input in lambda must be implicitly convertible to delegate parameter types Return type in lambda must be implicitly convertible to delegate return type
Variables declared in lambda are not accessible in enclosing method. Variable Scope Lambda can capture a variable or a parameter that is defined in enclosing method (unless it’s a ref or out parameter). Variables declared in lambda are not accessible in enclosing method. Return statement in lambda does not cause enclosing method to return.
Lambda Expression Trees Similar to expression lambdas but are not treated as delegates but rather as “data” – abstract syntax tree (AST) Has to be compiled before can be executed as delegate Can manipulate tree data at run time and compile to executable
Questions?