BlackWaspTM
C# Programming
.NET 3.5+

C# Lambda Expressions (2)

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.

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