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.