Practice question from Memory Fundamentals
The code creates 'int capturedValue = 42;' then returns a lambda '() => Console.WriteLine(capturedValue);'. The lambda outlives the method. Where does 'capturedValue' actually get stored? A. On the stack as part of the method's stack frame B. In a compiler-generated class on the heap C. In the lambda's method metadata in the assembly D. In static memory as a captured closure constant E. In thread-local storage for thread safety
Answer
B
Explanation
The lesson's closure section explained that when a lambda captures variables, the compiler transforms them into fields of a compiler-generated class allocated on the heap. This allows the captured variable to outlive the method's stack frame. Option A is wrong because stack memory is destroyed when the method returns. Options C/D/E don't match .NET's closure implementation mechanism.
More questions from Mastering Memory Management and Garbage Collection in .NET