C # pass by value

Hi guys, just wondering, 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 that in the above example, I have 2 copies on the stack, one for x and one for y ??

thank

+3
source share
3 answers

Yes, there will be two independent variables on the stack. They will also be in two different frames of the stack: one for mainand one for foo(in the absence of insertion). When fooreturned, the value xwill still be 1, not 5.

, #, , . , , .

. .

, , , : # , , . , x 1 , # x, y .

+14

- x main, y Foo.

+4

For more information, you also need to understand how parameter values ​​are passed. The reason that y in Foo does not affect x in Main is because they are in different frames of the stack. More information about the parameters of the data transfer type HERE .

+1
source

Source: https://habr.com/ru/post/1751959/


All Articles