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:

    Whatever offices of life are performed by women of culture and refinement are thenceforth elevated; they cease to be mere servile toils, and become expressions of the ideas of superior beings.
    Harriet Beecher Stowe (1811–1896)