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:

    “Compare the history of the novel to that of rock ‘n’ roll. Both started out a minority taste, became a mass taste, and then splintered into several subgenres. Both have been the typical cultural expressions of classes and epochs. Both started out aggressively fighting for their share of attention, novels attacking the drama, the tract, and the poem, rock attacking jazz and pop and rolling over classical music.”
    —W. T. Lhamon, U.S. educator, critic. “Material Differences,” Deliberate Speed: The Origins of a Cultural Style in the American 1950s, Smithsonian (1990)