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:

    Our books are false by being fragmentary: their sentences are bon mots, and not parts of natural discourse; childish expressions of surprise or pleasure in nature; or, worse, owing a brief notoriety to their petulance, or aversion from the order of nature,—being some curiosity or oddity, designedly not in harmony with nature, and purposely framed to excite surprise, as jugglers do by concealing their means.
    Ralph Waldo Emerson (1803–1882)