0Pricing
C# Academy · Lesson

Closures and Captured Variables

See how local functions capture state.

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));
    }
}

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