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:
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!