Developer knowledge network · moderated exchange

Сообщество UnreliableCode

Сообщество разработчиков, обратного проектирования и кодирования

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.