contactmatt
contactmatt

Reputation: 18600

c# strings are reference types - why when i change reference A's value, reference B doesn't change?

If strings in .NET are reference types, in the below code, why doesn't string2 change to "hi" after string1 is changed?

static void IsStringReallyAReference()
{
    string string1 = "hello";
    string string2 = string1;

    Console.WriteLine("-- Strings --");
    Console.WriteLine(string1);
    Console.WriteLine(string2);

    string1 = "hi";

    Console.WriteLine(string1);
    Console.WriteLine(string2);
    Console.Read();

}

/*Output:
hello
hello
hi
hello*/

Upvotes: 3

Views: 1009

Answers (4)

Upul Bandara
Upul Bandara

Reputation: 5958

This image might be helpful for you in order to understand the concept.

enter image description here

Upvotes: 6

Dienekes
Dienekes

Reputation: 1548

When you assigned "hi" to string1, what happened is that the variable string1 got assigned a new reference to an object on the heap which contains the text "hi".

Whereas, the variable string2 is still holding a reference of the object which has text "hello" within it.

Upvotes: 1

Chris Taylor
Chris Taylor

Reputation: 53699

That is because C# strings are immutable types, meaning that you cannot change the value of the instance.

When you change the string's value you are actually creating a new string and changing the reference to point to the new string after which your two reference variables no longer refer to the same string instance, one refers to the original string while the other refers to the new string instance with the new value.

Upvotes: 15

Chandu
Chandu

Reputation: 82893

That is because Strings are immutable types in .Net, i.e. every time you modify a string a new string is created.

From MSDN

A String is called immutable because its value cannot be modified once it has been created. Methods that appear to modify a String actually return a new String containing the modification.

Check the remarks section of this link: http://msdn.microsoft.com/en-us/library/system.string(v=VS.80).aspx

Upvotes: 2

Related Questions