Lambda Expressions

C# 3.0 extends the concept of anonymous methods and introduces lambda expressions, which are more powerful and flexible than anonymous methods.

Tip

Lambda expressions get their name from lambda calculus, which is a complicated topic, but in a nutshell, it’s a mathematical notation for describing functions. That’s pretty much what’s going on here; lambda expressions describe methods without naming them.

You define a lambda expression using this syntax:

(input parameters) => {expression or statement block};

The lambda operator => is newly introduced in C# 3.0 and is read as "goes to”. The left operand is a list of zero or more input parameters, and the right operand is the body of the lambda expression. Notice that => is an operator, which means that the preceding line of code is an expression. Just as x + x is an expression that returns a value—if x is 2, the expression returns the int value 4—a lambda expression is an expression that returns a method. It’s not a method by itself. It’s tricky to think of expressions as returning a method instead of a value, but at the beginning of this chapter, you wouldn’t have thought of passing a method as a parameter, either.

You can thus rewrite the delegate definition as follows:

theClock.OnSecondChange +=
    (aClock, ti) =>
    {
        Console.WriteLine("Current Time: {0}:{1}:{2}",
                           ti.hour.ToString( ),
                           ti.minute.ToString( ),
                           ti.second.ToString( ));
    };

You read this as "theClock’s OnSecondChange delegate adds an anonymous delegate defined by ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.