0
0
C Sharp (C#)programming~5 mins

Lambda with captures (closures) in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Lambdas with captures let you create small functions that remember values from outside their own code. This helps keep related data and behavior together.

When you want a quick function that uses variables from nearby code without passing them as parameters.
When you need to keep track of a changing value inside a small function, like counting or accumulating.
When you want to write cleaner code by avoiding extra classes or methods for simple tasks.
When you want to customize behavior on the fly, like sorting or filtering with specific rules.
Syntax
C Sharp (C#)
var lambda = () => expression;

// or with captures
int x = 5;
Func<int> lambdaWithCapture = () => x + 10;

Lambdas can access variables from the surrounding method or scope.

These captured variables are kept alive as long as the lambda exists.

Examples
This lambda captures variable a and adds 5 to it.
C Sharp (C#)
int a = 3;
Func<int> addFive = () => a + 5;
Console.WriteLine(addFive());
The lambda captures count and increases it each time it runs.
C Sharp (C#)
int count = 0;
Action increment = () => count++;
increment();
increment();
Console.WriteLine(count);
The lambda uses the captured prefix to create a greeting.
C Sharp (C#)
string prefix = "Hello";
Func<string, string> greet = name => prefix + ", " + name + "!";
Console.WriteLine(greet("Alice"));
Sample Program

This program shows a lambda that captures baseNumber. When baseNumber changes, the lambda uses the new value.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int baseNumber = 10;
        Func<int, int> addBase = x => x + baseNumber;

        Console.WriteLine(addBase(5));  // 15

        baseNumber = 20;  // Change captured variable
        Console.WriteLine(addBase(5));  // 25
    }
}
OutputSuccess
Important Notes

Captured variables are not copied; the lambda uses the original variable.

Changing the captured variable affects all lambdas that capture it.

Be careful with captured variables in loops to avoid unexpected results.

Summary

Lambdas with captures remember variables from outside their code.

This helps write small, flexible functions without extra classes.

Captured variables stay alive as long as the lambda needs them.