Link to home
Start Free TrialLog in
Avatar of brgdotnet
brgdotnetFlag for United States of America

asked on

Immutable strings in C# I need help understanding

Can someone explain to me the concept around immutable strings in C#. I thought immutable means that you can not change the content of a string. Yet in the compliler, the following code builds and runs and will ineed change the content of my string:

        String myString="hello";
        myString = myString + "GoodBye";
//  myString now = "helloGoodBye"
SOLUTION
Avatar of Blackninja2007
Blackninja2007

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The definition is correct. When you create a string in .Net; space on the Heap is allocated to that string.
Now when you alter the string, the old one is marked for garbage collection and space for the altered string is allocated on the heap.

It goes like this:
1. myString is loaded from memory to a register.
2. myString + "Goodbye"
4. the original heap allocation for myString is marked for GarbageCollection.
5. New memory is allocated for the altered myString
6. altered myString coppied to the new Heap location.

As you can see, technically strings are immutable internally.

Hope this helps,
John