First we create two string variables. Right now they are not referencing anything because they are not initialized:
string a1; string b1;
Then a line is created with the value "Hello" and a link is returned to this space in memory. a1 installed in this link:
a1 = "Hello";
Then a line is created with the value Goodbye, b1 is set to refer to it.
b1 = "Goodbye";
Next we do:
b1 = a1;
This assignment will copy the value of the link. Now b1 points to the line a1 points to, and goodbye is unavailable. Because strings are always allocated on the heap, the garbage collector eventually stops and clears the memory that Goodbye used because nothing refers to it. *
* Edit: Technically, this is probably not true, since the string constants will be interned and thus embedded in the interned table, but just say that these strings were obtained from the database or something else.
Then a line with the value "Wazzup?", a1 is given by reference to this:
a1 = "Wazzup?";
The string "Hello" still refers to the variable b1 , so it is safe. With that in mind:
// Prints "Wazzup" because we just set a1 to a reference to that string Console.WriteLine(a1); //Prints "Hello" because b1 still has its value it had copied over from a1 Console.WriteLine(b1);
Hope this clarifies the situation.
source share