RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


From Delegate to Lambda : Page 3

The key to understanding lambda expressions lies in understanding delegates.

Stepping It Up: Anonymous Methods in C#
Author's Note: Because VB .NET 8.0 does not support the concept of anonymous methods, this section applies only to C#.

C# 2.0 introduced the concept of anonymous methods. In the pre-C# 2.0 era, the only way to use delegates was to create a named method. In C# 2.0, Microsoft added a feature to allow inline declaration of a method using the delegate keyword and a code block. So what does this look like?

   List<int> even = 
   Select( _numbers, 
   delegate( int x ) { return ( x % 2 == 0 ); } );
Instead of passing the name of an existing method, you can use the delegate keyword to define an inline function. The snippet shows the creation of a method that takes an integer as a parameter, has a method body, and returns a Boolean value; in other words, the anonymous method matches with the Filter-delegate.

As you will probably agree, this does nothing for readability-in the C# 2.0 era, the use of this type of inline delegate creation was largely reserved to generated code. However, out of the darkness came light and now lambda expressions are here to provide a readable syntax for this kind of inline delegate creation.

Lambda Expressions: Readable Anonymous Methods
Lambda expressions allow you to create delegates in a very concise syntax. And good news for the VB developers: VB 9.0 also supports lambda expressions!

Lambda Expressions in C#
Here's the definition of lambda expressions from the C# Programming Guide on MSDN):

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x."

So a lambda expression is an anonymous method. In the previous section, you saw that anonymous methods are delegates; therefore lambda expressions are nothing more than delegates.

Author's Note: In Visual Basic, the RemoveHandler statement is an exception to the lambda = delegate rule. You cannot pass in a lambda expression for the delegate parameter of RemoveHandler.

You can substitute a named method for a lambda expression when you call the Select method:

   Filter f = x => x % 2 == 0;
   List<int> even = Select( _numbers, f );
The snippet shows that you're defining a variable f of type Filter and assigning a lambda expression to it. You then use the delegate to call the Select method.

I want to zoom in on the following lambda expression:

   x => x % 2 == 0
This lambda expression contains an input variable x that goes to x modulo 2 and compares the result to 0, returning a true/false value. Notice how there are no brackets {} and there is no return keyword. If a lambda expression consists of just one line, the result of that one line is automatically assumed to be the return value and brackets are not needed:

   x => { x++; return x % 2 == 0; }
The above snippet increments the value of x by 1 before performing the modulo 2 division. Because the code block consists of more than one statement, you now need the brackets and you also need to include the return keyword.

Another significant feature is the ability of the compiler to infer the types involved in the lambda expression. Because a lambda expression is always assigned to a delegate, the compiler will look at the types expected by the delegate and use those when validating your code. For instance, changing the lambda expression as shown below would change the return type of the expression from a Boolean to an integer:

   x => x % 2
The Filter delegate expects a Boolean return type, hence your code will not compile.

Lambda Expressions in Visual Basic
From the VB Programming Guide on MSDN:

A lambda expression is a function without a name that calculates and returns a single value. Lambda expressions can be used wherever a delegate type is valid.

Because VB never supported anonymous methods, there is no reference to them. Instead it is instantly made clear that lambda expressions are delegates. The syntax for lambda expressions in VB adds the Function keyword, going back to the Select method. Calling the Select method using a lambda expression would look like this:

   Dim f As Filter = Function(x) x Mod 2 = 0
   Dim even = [Select](_numbers, f)
Again, there is no Return statement. In VB a lambda expression can consist of only a single line, because there's no End Function statement. Just like C#, the framework infers the type of x from the delegate to which the lambda expression is assigned.

Note of caution: If you use VB with the Option Strict Off setting, then side effects may occur. The following code performs an implicit cast from Integer to Boolean, which is probably not the desired effect. It is better to use the Option Strict On setting:

   Dim f As Filter = Function(x) x Mod 2
   Dim even = [Select](_numbers, f)
The new syntax offered by lambda expressions can be fairly confusing, that is, until you realize what they are. The concise notation allows for very readable and powerful programming.

Filtering and simple operations is where lambda expressions excel and lambda expressions are one of the cornerstones of the LINQ extensions methods.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date