Click here to Skip to main content
15,881,455 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why is the output of this code a.x 10 b.x 20 a.x 30 b.x 30

rather than a.x 10 b.x 20 a.x 20 b.x 30

why does a.x become 30 when its not set anywhere



C#
class myClass
 {
     public int x;
    public myClass()
     {

     }
 }


 class MainClass
 {
     public static void Main()
     {
         myClass referenceA = new myClass();
         myClass referenceB = new myClass();

         referenceA.x = 10;
         referenceB.x = 20;
         Console.WriteLine("a.x {0}, b.x {1}",referenceA.x,referenceB.x);

         referenceA = referenceB;
         referenceB.x = 30;
         Console.WriteLine("a.x {0}, b.x {1}", referenceA.x ,referenceB.x);
         Console.ReadLine();
     }
 }
Posted
Updated 8-Oct-14 8:52am
v4
Comments
[no name] 8-Oct-14 11:39am    
It is set somewhere it is set when you referenceA = referenceB;
Maciej Los 8-Oct-14 11:53am    
Use 'Reply' widget to post comment to another comment, otherwise Wes Aday never will see your comment.

When you set referenceA=referenceB both variables are now pointing to the same thing, the same memory.
So when you update referenceB you can access exactly the same data with referenceA
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 8-Oct-14 13:20pm    
5ed.
—SA
Maciej Los 8-Oct-14 14:57pm    
+5
When you execute: referenceA = referenceB;

You assign the pointer to the instance of the class 'MyClass in 'referenceB to 'referenceA. You have "thrown away" the first instance of 'MyClass you created ... it will be garbage collected at the right time.

After that, any change to 'referenceB will also be a change to 'referenceA because: they both point to the same instance of 'MyClass.

Now, if you assign a value to 'referenceA, you will also change the value of 'referenceB.
 
Share this answer
 
Comments
CHill60 8-Oct-14 11:58am    
Overlap! I'm a slower typer. +5
Sergey Alexandrovich Kryukov 8-Oct-14 13:20pm    
5ed.
—SA
Maciej Los 8-Oct-14 14:57pm    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900