Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

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 months ago · 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 months ago · 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 months ago · 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.