๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

C# Lambdas

A lambda is a short method without a name. A lambda can be stored in a delegate variable or passed to another method.

An expression lambda as a value

The lambda adds its two inputs. The Operation variable holds the lambda.

using System;

delegate int Operation(int a, int b);

class Program
{
    static void Main(string[] args)
    {
        Operation add = (a, b) => a + b;
        Console.WriteLine(add(3, 4));
    }
}

A lambda passed to a helper

Apply receives a lambda as its first argument. Apply calls the lambda with the other two values.

using System;

delegate int Operation(int a, int b);

class Program
{
    static int Apply(Operation op, int x, int y)
    {
        return op(x, y);
    }

    static void Main(string[] args)
    {
        int result = Apply((a, b) => a * b, 6, 5);
        Console.WriteLine(result);
    }
}

A statement lambda

Braces hold a full statement body. The return statement gives the result.

using System;

delegate int Operation(int a, int b);

class Program
{
    static void Main(string[] args)
    {
        Operation subtract = (a, b) =>
        {
            int result = a - b;
            return result;
        };
        Console.WriteLine(subtract(10, 4));
    }
}

A captured counter

The lambda uses the count variable from Main. Each call adds one and prints the new value.

using System;

delegate void Step();

class Program
{
    static void Main(string[] args)
    {
        int count = 0;
        Step next = () =>
        {
            count = count + 1;
            Console.WriteLine(count);
        };
        next();
        next();
    }
}

Example

using System;

delegate string Greeter(string name);

class Program
{
    static void Main(string[] args)
    {
        Greeter greet = name => "Hello, " + name;
        Console.WriteLine(greet("Hana"));
        Console.WriteLine(greet("Rex"));
    }
}

Key points

  • The => symbol separates the inputs from the body.
  • An expression lambda returns its expression value directly.
  • A statement lambda uses braces and a return statement.
  • A lambda can use a variable from the code around it.
  • Changes to a captured variable stay visible between calls.

In this example, the lambda takes one name as input. A single input needs no parentheses. Each call builds a greeting from the name it receives.

Note

The delegate type gives the lambda its parameter types.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the second call to the captured counter print?