简体   繁体   中英

c# pass by value

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 main and one for foo (assuming no inlining). When Foo returns, the value of x will 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 x does have to have the value of 1 at the end of your code, but a valid C# compiler could have put both x and y on the heap.

您理解正确 - x的值将放在main函数的堆栈框架中的堆栈上,而y的值将放在Foo堆栈框架中的堆栈上。

For more details you also need to understand how value parameters are passed. The reason that y in Foo is not affecting x in Main is that they are in different stack frames. More details on passing value type parameters are HERE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM