How is the C# Stack accessed by the CLR?

Variables aren't stacked individually; the stack contains "frames." Each frame contains all variables (locals, parameters, etc) required by the current method call. So in your example, a and b exist alongside eachother in the same frame, and there's no need to remove either of them. When the method foo completes, the entire stack frame is popped from the stack, leaving the calling method's frame at the top.

The wikpedia article may provide some enlightenment.


The call stack is not strictly a "pure" stack where you can interact only with the top element. In the call stack you're stacking whole function calls and/or whole variable scopes, not variables.

For example, if a new function, say foo(), is called, it places its two variables, a and b, on top of the stack and has full access to them. It is (normally) not aware of anything below those variables on the stack.

Let's take a look at this code:

void foo() { // << Space is allocated on the stack for a and b.
             // << Anything in this scope has full access to a and b.
             // << But you cannot (normally) access anything from the
             // << calling function.
    var a = 1;
    var b = 2;

    if (a == 1) {  // << Another variable scope is placed on the stack.
                   // << From here you can access a, b and c.
        var c = 3;
    } // << c is removed from the stack.
} // << a, b and anything else in foo() is removed from the stack.

Please note that, while you're talking about fields, a and b are called local variables.

Maybe the following simplified logical representation can clear up things. Before the call to Console.WriteLine, the top of the stack would look something like this:

|5| // b
|1| // a

Inside Console.WriteLine, an additional stackframe is added for its parameter (called value, which gets a copy of the variable a):

|1| // value = a
|5| // b
|1| // a

Once Console.WriteLine returns, the top frame is popped and the stack becomes again:

|5| // b
|1| // a

Tags:

C#

Clr

Stack

Heap

Cil