Download presentation
Presentation is loading. Please wait.
1
Lambda Expressions By Val Feldsher
2
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
3
Lambdas are less verbose than anonymous methods Anonymous:
Lambda vs. Anonymous Lambdas are less verbose than anonymous methods Anonymous: Lambda
4
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
5
Lambdas can contain multi-line statements on the right hand side
Statement Lambdas Lambdas can contain multi-line statements on the right hand side
6
Standard Query Operators
Many standard query operators (LINQ) take a generic delegate of type Func<T, Tresult> as a parameter.
7
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
8
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.
9
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
10
Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.