In this fiddle, we are assigning a static field to an instance field. When we change the static one, the instance one still has the initial value. Why is that? We thought that both should be referring to the same object but it seems that they're not.
using System;
public class Program
{
public static string StaticString;
public string InstanceString;
public static void Main()
{
Program.StaticString = "foo";
var p = new Program();
p.InstanceString = Program.StaticString;
Program.StaticString = "bar";
Console.WriteLine(p.InstanceString);
}
}
We were really expecting this to print bar
but it printed foo
.
In this fiddle, we are assigning a static field to an instance field.
Right. That copies the current value of the static field to the instance field. It doesn't tie the variables together forever - it just copies the current value.
When we change the static one, the instance one still has the initial value.
Yes, because you've just changed the value of the static field - why would that change the value of the instance field? They're independent variables - they just happened to hold the same value at one point. Importantly, you haven't made any change to the string object that the value of the instance field refers to. (And indeed you can't make changes to the string object, because strings are immutable.)
I view variables as being like pieces of paper with the values written on them. When the variable is a reference type, the value on the piece of paper is just a way of navigating to an object - like a street address. But copying one variable to another is always just a matter of copying what's written on one piece of paper onto another. So for example, suppose I have:
House x = new House();
House y = x;
x.DoorColor = Black;
x = null;
Console.WriteLine(y.DoorColor);
That's like:
x
, and writing a street address on itx
onto a piece of paper called y
x
and painting the door blackx
y
and reporting the colour of the doorThat last step would report that the door is black, right? Rubbing out the value written on piece of paper x
doesn't change either what's written on piece of paper y
, or anything about the house.
This isn't quite the same set of steps as in your code, but hopefully it will shed more light on it...
See more on this question at Stackoverflow