Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
Tutorial

Preventing Closure Memory Leaks using Static Local Functions and Static Lambdas in C# [StackOverflow Architecture Guide]

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Өкіл: 103
Қосылу күні: Apr 2018
Хабарламалар: 40
Рахмет: 24
1 ай бұрын · Jul 10, 2026 10:45 AM
#1

Why accidental closure captures cause silent memory leaks in long-running services:

When a local function or lambda references a variable in the outer scope, the compiler allocates a hidden display class on the heap, keeping all outer variables alive in memory!

The Fix: static modifier:

CSHARP
public void ProcessOrder(Order order)
{
    int multiplier = 2;
    
    // 'static' keyword guarantees this local function CANNOT capture outer scope variables!
    static int CalculateTax(int amount)
    {
        return amount * 10 / 100;
    }
}

If you accidentally try to reference multiplier inside CalculateTax, the compiler produces a compile-time error!

profiler_pat
Performance Hunter
MEMBER
Өкіл: 146
Қосылу күні: Aug 2019
Хабарламалар: 33
Рахмет: 31
1 ай бұрын · Jul 10, 2026 2:14 PM
#2

Adding static to local functions and lambdas (static (x) => ...) is a zero-cost way to enforce zero allocations.

roslyn_source_gen
Roslyn Compiler Dev
MEMBER
Өкіл: 120
Қосылу күні: Feb 2020
Хабарламалар: 12
Рахмет: 75
1 ай бұрын · Jul 11, 2026 2:21 AM
#3

We enabled the Roslyn analyzer rule that flags all non-static local functions that don't need closure captures.