Click here to Skip to main content
14,176,451 members
Rate this:
 
Please Sign up or sign in to vote.
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



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
Wes Aday 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.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

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
   
Comments
   
5ed.
—SA
Maciej Los 8-Oct-14 14:57pm
   
+5
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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.
   
Comments
CHill60 8-Oct-14 11:58am
   
Overlap! I'm a slower typer. +5
   
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web05 | 2.8.190525.1 | Last Updated 8 Oct 2014
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100