C # - find a way out

I have the following C # code below.

Object first = 5; 
Object second = 10; 
second = first;
Console.WriteLine(first + "    " + second);


 Object a = 3; 
 Object b = a; 
 a = 6;
 Console.WriteLine(a + "    " + b);

      

I am getting the following output:

5 5
6 3

      

In fact, I expect "6 6" to be the second. Can anyone explain where I am going wrong?

Regards, Justin Samuel.

+2


source to share


5 answers


Line

a = 6;

      



assigns a a

reference to the built-in int new .
b

continues to refer to the value (3) that was boxed earlier.

+4


source


Each variable Object

will contain int

which is the type of the value. a

and there b

will be two different instances, so changing the value a

(which essentially means the reference a

refers to a new instance of int) will not change the value b

. You can modify your first code example to get a similar result:



Object first = 5; 
Object second = 10; 
second = first;
first = 8;
Console.WriteLine(first + "    " + second); // prints "8    5"

      

+1


source


Integer values ​​are value types, not references.

When you write this

object a = 3;
object b = a;

      

you assign the value 3 to b. Subsequently, when

a = 6;

      

you assign the value 6 to a and b has no effect because it was assigned the value 3.

+1


source


When you set a = 6, its only setting a, b remains 3. (this was expected)

0


source


static unsafe void Main()
    {

        Object first = 5;
        Object second = 10;
        second = first;
        Console.WriteLine(first + "    " + second);

        int i = 3;
        int y = 6;
        int* a = &i;
        int** b = &a;
        a = &y;
        Console.WriteLine(*a + "    " + **b);}

      

execute / unsafe

5 5
6 6

:-). I would not recommend writing code this way though =)

0


source







All Articles