3

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*/
0

4 Answers 4

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 from my side. Just a quick question here. When we pass the string by reference to a method and then change the value of the string in the method, we get the updated value of the string after the method execution gets completed. What are the fundamentals behind that?
@samar, in this case you are creating a reference to the reference, so when the string is changed (new string created) the initial reference is updated to reference the new string. This extra level of indirection give the appearance that the string has changed, but in reality the reference has been changed to point to the new string. Hope that makes some sense.
6

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

enter image description here

Comments

2

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

1 Comment

Mutability isn't relevant for this particular question.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.