Lambda Expressions (C#)

Lambda expressions allow us to define anonymous expressions. You can use lambda expressions where where you might use a delegate function.

Lambda expressions are defined using the lambda operator =>. There are two types of lambda expressions:

  • An expression lambda which is defined by an expression.
  • A statement lambda which is defined by a statement block.

For example:

// Expression lambda:
(x) => x * x;

// Statement lambda
(x) => { Console.WriteLine(x); }

Example: Graph plotter

Lambda expressions are a convenient way to define maths functions. Imagine we had a graph plotter class which allows you to specify a maths function to display. Such a class might look like this:

class GraphPlotter
{
    public static void Plot(Func<double, double> f)
    {
        // Code to plot graph...
    }
}

Note that we are using Func which is a predefined delegate we covered in Delegates and Events.

Then if we want to plot the graph of y=x2y=x^2, we can simply write:

GraphPlotter.Plot(x => x * 2);

Example: LINQ

Lambda expressions are very useful when using LINQ. For example, the following code shows how to sort an array of integers in reverse orders:

int[] values = { 2, 6, 7, 8, 5 };
var orderedValues = values.OrderBy(x => -x);
Console.WriteLine(string.Join(" ", orderedValues));

Captured variables

A lambda expression can refer to variables in the enclosing scope. These are called captured variables. Variables are captured by reference.

Here is an example of captured variables in action:

int i = 0;
var printer = new Action(() => { Console.WriteLine(i); });
for (i = 0; i < 10; i++)
    printer.Invoke();

Since i is captured by reference, the output of this program is:

0
1
2
3
4
5
6
7
8
9