March 19, 2009

Lambda Rules

  • A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
  • All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x."
  • Lambdas are not allowed on the left side of the is or as operator.
  • The lambda must contain the same number of parameters as the delegate type.
  • Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter.
  • The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.

The following rules apply to variable scope in lambda expressions:

  • A variable that is captured will not be garbage-collected until the delegate that references it goes out of scope.
  • Variables introduced within a lambda expression are not visible in the outer method.
  • A lambda expression cannot directly capture a ref or out parameter from an enclosing method.
  • A return statement in a lambda expression does not cause the enclosing method to return.
  • A lambda expression cannot contain a goto statement, break statement, or continue statement whose target is outside the body or in the body of a contained anonymous function.
Expressions Lambda
  • A lambda expression with an expression on the right side is called an expression lambda.
(input parameters) => expression
  • All restrictions that apply to anonymous methods also apply to lambda expressions.
  • The parentheses are optional only if the lambda has one input parameter; otherwise they are required. Two or more input parameters are separated by commas enclosed in parentheses:
    (x, y) => x == y
  • Sometimes it is difficult or impossible for the compiler to infer the input types. When this occurs, you can specify the types explicitly as shown in the following example:
    (int x, string s) => s.Length > x
  • Specify zero input parameters with empty parentheses:
    () => SomeMethod()
Statements Lambda
  • A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces:
    (input parameters) => {statement;}
Lambdas with the Standard Query Operators
  • A standard query operator, the Count method, is shown here:
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
    int oddNumbers = numbers.Count(n => n % 2 == 1);