BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 3.5+

C# Lambda Expressions

C# 3.0 and the .NET framework 3.5 introduced lambda expressions to the language. Lambda expressions permit the creation of anonymous functions with a very concise syntax. They are often used to quickly create delegates for use in LINQ queries.

What is a Lambda Expression?

Lambda expressions are a feature of C# 3.0 and the .NET framework 3.5. They allow the creation of anonymous methods or functions using a very concise syntax, similar to that of lambda calculus. Lambda expressions can be categorised as expression lambdas and statement lambdas. Expression lambdas include an expression consisting of operands and operators. Statement lambdas include a code block containing one or more statements.

The Lambda Operator

The syntax for expression lambdas is as follows:

(params) => expression

This syntax is easily identifiable as a lambda expression, as it uses the lambda operator (=>). To the left of the operator are the parameters for the anonymous method being defined. The parameters, if any exist, are provided as a comma-separated list within parentheses. The parentheses are optional where only one parameter is present. To the right of the operator is an expression that may use the provided arguments. This can be thought of as the body of the anonymous method.

The following shows a simple lambda expression that accepts a single parameter and returns the provided value plus one. Note that the parentheses around the parameter have been omitted as they are optional in this case.

x => x + 1

The lambda cannot be executed in the above form. To demonstrate its use, we can link it to a pre-defined delegate and then call the delegate. This is shown below in the context of a console application.

delegate int lambda(int input);

static void Main(string[] args)
{
    lambda addOne = x => x + 1;
    Console.WriteLine(addOne(1));   // Outputs "2"
}

In this example, the lambda expression provides a concise syntax. The functionality could also have been created using an anonymous method or a standard method. The equivalent anonymous method is shown below. In this case the difference between the two examples is small. However, as the complexity of the function increases, a carefully constructed lambda version can be much shorter.

delegate int lambda(int input);

static void Main(string[] args)
{
    lambda addOne = delegate(int x) { return x + 1; };
    Console.WriteLine(addOne(1));
}

One of the key uses of lambda expressions is with the standard query operators. Here the simplicity of the expression can vastly improve the readability of a query, particularly for complex queries that use multiple lambdas. The following is a simple example that extracts the list of even numbers from an array containing the values from one to ten. The lambda expression in this case is a predicate, as it returns a Boolean value. The predicate is compared to each of the values in the array and only those where the lambda returns true are included in the list of even numbers.

int[] oneToTen = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNumbers = oneToTen.Where(n => n % 2 == 0);

foreach (int i in evenNumbers)
    Console.Write("{0} ", i);       // Outputs "2 4 6 8 10 "

Using Multiple Parameters

As with anonymous methods, lambda expressions can use multiple parameters. To create such a lambda, the parameters should be defined as a comma-separated list and provided between parentheses. The following example shows the use of a lambda expression that multiplies three numbers, each provided as an argument.

delegate long multi(int x, int y, int z);

static void Main(string[] args)
{
    multi multiply = (x, y, z) => x * y * z;
    Console.WriteLine(multiply(2, 3, 4));   // Outputs "24"
}

It is also possible to declare a lambda expression that uses no parameters. In this case, an empty pair of parentheses should be included to the left of the lambda operator. This can be demonstrated by executing the following example. Here a single value representing a tax rate is returned by the lambda expression.

delegate double noparams();

static void Main(string[] args)
{
    noparams taxRate = () => 17.5;
    Console.WriteLine("{0}%", taxRate());
}

Specifying Explicit Types

In most cases, the parameter types for lambda expressions are inferred using the signature of the delegate. There are some cases where this is not possible and compilation will fail. In these situations, the types can be specified explicitly. When stating the types, parentheses are always required. For example:

(int x) => x + 1

Statement Lambdas

Statement lambdas use a similar syntax to expression lambdas in their use of the lambda operator and parameter declaration. However, instead of an expression appearing to the right of the operator, a code block of one or more statements is provided. Typically the number of statements in a statement lambda is small.

(params) => { statements }

The following example shows a statement lambda that generates a random number, outputs it to the console and returns it. The code block of the lambda spans several lines for readability.

noparams randomiser = () =>
{
    int random = new Random().Next();
    Console.WriteLine("Random number generated - {0}", random);
    return random;
};
Console.WriteLine(randomiser());
20 March 2010