I am just wondering to take the following example:
public void main()
{
int x = 1;
Foo(x);
}
public void Foo(int y)
{
y = 5;
}
We know that C# arguments are passed by value for value types. Does this mean in the above example, that I have 2 copies on the stack, one for x and one for y?
Yes, there will be two independent variables on the stack. They will be in two different stack frames, too – one for
mainand one forfoo(assuming no inlining). WhenFooreturns, the value ofxwill still be 1, not 5.In fact, arguments are always passed by value by default in C#, both for reference types and value types. The only difference is that for reference types, the argument value is a reference – not the object itself.
See my article on parameter passing for a lot more detail on this.
Note that the actual behaviour of what goes on the stack is an implementation detail: the C# compiler has to make sure that a program behaves as defined in the specification, but that doesn’t mandate stack or heap behaviour. So
xdoes have to have the value of 1 at the end of your code, but a valid C# compiler could have put bothxandyon the heap.