0Pricing
C# Academy · Lesson

Closures and Captured Variables

See how local functions capture state.

Closures and Captured Variables is a free C# Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Closures Over Local State

A local function (or lambda) can read and modify variables from its enclosing method. This is called capturing, and the function plus the variables it captures form a closure.

Capturing a Variable

The local function uses factor from the enclosing method directly. It does not receive it as a parameter; it captures it from the surrounding scope.

using System;

public class Program
{
    public static void Main()
    {
        int factor = 3;
        int Scale(int n) => n * factor; // captures factor

        Console.WriteLine(Scale(5));
        Console.WriteLine(Scale(10));
    }
}

Captured Variables Are Live References

A closure captures the variable, not a snapshot of its value. If the variable changes after the function is defined, the function sees the new value.

using System;

public class Program
{
    public static void Main()
    {
        int offset = 10;
        int Add(int n) => n + offset;

        Console.WriteLine(Add(1)); // 11
        offset = 100;
        Console.WriteLine(Add(1)); // 101 - sees updated offset
    }
}

Mutating Captured Variables

A closure can write to a captured variable, and the change is visible in the enclosing method too. This makes closures useful for accumulating state.

using System;

public class Program
{
    public static void Main()
    {
        int count = 0;
        void Tick() => count++;

        Tick(); Tick(); Tick();
        Console.WriteLine(count); // 3
    }
}

Returning a Closure

When you return a lambda that captured locals, those variables outlive the method. The captured state lives as long as the delegate does.

using System;

public class Program
{
    static Func<int> MakeCounter()
    {
        int count = 0;
        return () => ++count; // captures count
    }

    public static void Main()
    {
        var next = MakeCounter();
        Console.WriteLine(next());
        Console.WriteLine(next());
        Console.WriteLine(next());
    }
}

Independent Closures

Each call to a factory creates a fresh set of captured variables. Two counters built this way do not interfere with each other.

using System;

public class Program
{
    static Func<int> MakeCounter()
    {
        int count = 0;
        return () => ++count;
    }

    public static void Main()
    {
        var a = MakeCounter();
        var b = MakeCounter();
        Console.WriteLine(a()); // 1
        Console.WriteLine(a()); // 2
        Console.WriteLine(b()); // 1 - separate state
    }
}

The foreach Capture Fix

In modern C#, the foreach loop variable is fresh per iteration, so closures capture the expected value. Each lambda below remembers its own item.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var actions = new List<Action>();
        foreach (var i in new[] { 1, 2, 3 })
            actions.Add(() => Console.WriteLine(i));

        foreach (var act in actions) act(); // prints 1, 2, 3
    }
}

Capturing in a for Loop

A classic pitfall: a single for loop variable is shared across iterations, so all closures see its final value. Copy it into a per-iteration local to capture distinct values.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var actions = new List<Action>();
        for (int i = 0; i < 3; i++)
        {
            int copy = i; // fresh local each iteration
            actions.Add(() => Console.WriteLine(copy));
        }
        foreach (var act in actions) act(); // prints 0, 1, 2
    }
}

Closures Capture by Reference, Not Value

Because capture is by reference, mutating the original after capture is observed by the closure. Remember this when the timing of reads and writes matters.

using System;

public class Program
{
    public static void Main()
    {
        string message = "first";
        Action print = () => Console.WriteLine(message);

        print();          // first
        message = "second";
        print();          // second
    }
}

Practical Use: Configurable Behavior

Closures let you build small functions pre-loaded with context. Here a discount function captures a rate, producing a reusable, configured calculator.

using System;

public class Program
{
    static Func<double, double> MakeDiscount(double rate)
        => price => price * (1 - rate);

    public static void Main()
    {
        var tenOff = MakeDiscount(0.10);
        var halfOff = MakeDiscount(0.50);
        Console.WriteLine(tenOff(100));
        Console.WriteLine(halfOff(100));
    }
}

Try It Yourself

Build a counter factory whose returned closure keeps private state alive, then create two independent counters from it.

using System;

public class Program
{
    static Func<int> MakeStepper(int step)
    {
        int current = 0;
        return () => { current += step; return current; }; // captures current and step
    }

    public static void Main()
    {
        var byTwos = MakeStepper(2);
        var byTens = MakeStepper(10);
        Console.WriteLine(byTwos()); // 2
        Console.WriteLine(byTwos()); // 4
        Console.WriteLine(byTens()); // 10 - separate state
    }
}

Quick Check

Reason about how capture works.

Recap

Closures capture enclosing variables by reference.

  • The function sees the variable current value, including later changes.
  • It can mutate captured variables, sharing state with the method.
  • Returned closures keep their captured variables alive.
  • Use a per-iteration local in a for loop to capture distinct values.

Frequently asked questions

Is the “Closures and Captured Variables” lesson free?

Yes — the full text of “Closures and Captured Variables” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Closures and Captured Variables”?

See how local functions capture state. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Closures and Captured Variables” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Declaring Local Functions
  2. Closures and Captured Variables
  3. Static Local Functions
  4. Local Functions vs Lambdas
← Back to C# Academy