I've been playing around trying to thoroughly understand Reference and Value types. Just when I thought I had it, I came across this scenario...
I created a class that would contain a single object.
class Container
{
public object A {get; set;}
}
When I create an instance of this Container class (a) I am creating instance of a reference type. I assign an integer to the object within the class. As far as I am aware, this will be boxed as an object, another reference type.
int start = 1;
Container a = new Container{ A=start };
I create another instance of the Container class (b), but assign the value of the first container to it, the value of b is now a reference to a.
Container b = a;
As expected when I print out the value of both a.A and b.A, they are the same.
Console.WriteLine("a.A={0},b.A={1}",a.A,b.A);
//a.A=1,b.A=1
And, as expected, when I change the value of a.A the value of b.A also changes due to them referencing the same object.
a.A = 2;
Console.WriteLine("a.A={0},b.A={1}",a.A,b.A);
// a.A=2,b.A=2
Now I decided to try this using individual local objects. Again, I box the integer into the first object and assign the value of the first object to the second. I believe the object, at this point, should be a reference type so c and d should reference the same object. Without changing anything they return the same value.
int start = 1;
object c = start;
object d = c;
Console.WriteLine("c={0},d={1}",c,d);
// c=1,d=1
Like before, when changing the value of the initial object, I expect the value of both objects to be the same.
c = 2;
Console.WriteLine("c={0},d={1}",c,d);
// c=2,d=1
When I print the result for these two objects, the value of d does not change like before.
Can someone please explain why the assignment is different in this scenario to the previous?
Thanks