brgdotnet
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"
String myString="hello";
myString = myString + "GoodBye";
// myString now = "helloGoodBye"
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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