0

With a method/function without any additional inside-blocks of code, all the variables are just local and they exist on the stack (with reference types it's the actual reference that's on the stack). But what about the variables declared in some sort of block inside the body of the method?

Are the variables declared inside such an inner block still initialized on the stack when the method is called, but it's just that the compiler is somehow smart, and only allows you use them when inside the block where they are declared? Or are such blocks of code actually treated as methods/functions in some sense? I.e. local variables of the outside scope are passed as arguments to the block, or something like that.

John P
  • 251
  • 1
  • 6
  • `but it's just that the compiler is somehow smart, and only allows you use them when inside the block where they are declared` - yes. – GSerg Feb 07 '20 at 19:19
  • @GSerg Your first comment seems to be enough of an answer, if it's true. I'm not sure that question you posted is related to this - it considers what happens with the local variable of a method/function, and how release/debug mode effects the resulting code. But what happens with a variable declared in a block that is inside the code block of a method, when that inside block ends? Technically, it's not accessible any longer, but what is actually happening - does it actually stop existing, or is it still on the stack, just not accessible, only disappearing when the actual method ends. – John P Feb 07 '20 at 19:56
  • The stack frame is set up upon entry, so the space for all local variables exists for the duration of the method. Changing how much stack is allocated for local variables because of changes in variable scope is far too complex and not work the cycles. The compiler's management of variable scope is an abstraction over the allocated stack space and allows access to those locations only when they're in scope. – madreflection Feb 07 '20 at 20:56
  • 3
    Also, [The Stack Is An Implementation Detail](https://blogs.msdn.microsoft.com/ericlippert/2009/04/27/the-stack-is-an-implementation-detail-part-one/), so it's possible that an implementation may not use the stack for some or all methods. – madreflection Feb 07 '20 at 20:57
  • The C# compiler generates instructions in the .NET intermediate language (IL, a.k.a. MSIL or CIL), and those instructions are then converted to machine code at runtime by the Just-In-Time (JIT) compiler. Are you interested in the way C# implements this scenario in IL, the way the JIT then converts the IL into machine code, or both? – Joe Sewell Feb 07 '20 at 21:01

0 Answers0