views:

99

answers:

5
+2  Q: 

C# - Find output

Hi All, 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 get the following output:

5 5
6 3

Actually I am expecting "6 6" as the second set. Can anybody explain where I am wrong?

Regards, Justin Samuel.

A: 

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

Mark Redman
+1  A: 

Each Object variable will contain an int which is a value type. a and b will be two different instances, so changing the value of a (which essentially means to have a reference a new int instance) will not alter the value of b. You can alter your first code sample to produce a similar result:

Object first = 5; 
Object second = 10; 
second = first;
first = 8;
Console.WriteLine(first + "    " + second); // prints "8    5"
Fredrik Mörk
He does not change the (int) value of `a` but makes `a` reference a different object.
Henk Holterman
@Henk: yes, that is a more clear way of expressing it.
Fredrik Mörk
Henk is absolutely correct.
Ivan Zlatanov
+1  A: 

Integers are value types, not references.

When you write this

object a = 3;
object b = a;

you assign the value 3 to b. The subsequently, with

a = 6;

you assign the value 6 to a, and b is not affected because it was assigned the value 3.

Mark Seemann
But `a` and `b` are references (to boxed int's).
Henk Holterman
+4  A: 

The line

a = 6;

assigns a with the reference to a newly boxed int.
b keeps referencing the value (3) that was boxed earlier.

Henk Holterman
A: 
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);}

complit with /unsafe

5    5
6    6

:-). i'd not recommend to write code in this way though =)

Trickster