C Sharp Syntax - Anonymous Methods - Lambda Expressions

Lambda Expressions

This is a feature of C# 3.0.

Lambda expressions provide a simple syntax for inline functions that are similar to closures. Functions with parameters infer the type of the parameters if other is not explicitly specified.

// => // With parameters n => n == 2 (a, b) => a + b (a, b) => { a++; return a + b; } // With explicitly typed parameters (int a, int b) => a + b // No parameters => return 0 // Assigning lambda to delegate Func f = (a, b) => a + b;

Multi-statement lambdas have bodies enclosed by brackets and inside of them code can be written like in standard methods.

(a, b) => { a++; return a + b; }

Lambda expressions can be passed as arguments directly in method calls similar to anonymous delegates but with a more aesthetic syntax.

var list = stringList.Where(n => n.Length > 2);

Lambda expressions are essentially compiler-generated methods that are passed via delegates. These methods are reserved for the compiler only and can not be used in any other context.

Read more about this topic:  C Sharp Syntax, Anonymous Methods

Famous quotes containing the word expressions:

    Each child has his own individual expressions to offer to the world. That expression can take many forms, from artistic interests, a way of thinking, athletic activities, a particular style of dressing, musical talents, different hobbies, etc. Our job is to join our children in discovering who they are.
    Stephanie Martson (20th century)