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
- Declaring Local Functions
- Closures and Captured Variables
- Static Local Functions
- Local Functions vs Lambdas