I have the following piece of code
List<String> l = new List<String>();
String s = "hello";
l.Add(s);
s = "world";
When I set up some breakpoints and go through the program, after executing the last line, the value in the list is still hello instead of world.
Shouldn’t it equal world ? Isn’t a string an object, and am I not just inserting a pointer into the list? Later on if I change the string to point to a different value (“world”), why is my list still referencing the old value?
How can I get my desired effect ?
Thanks a lot!
Strings are immutable so that won’t work. When you attempt to set into it, you actually drop the pointer to the old string and create a new one under the hood.
To get the desired effect, create a class that wraps a string:
And use this in your list. Then references will point to the class, but you can contain the string value inside. To make it even better, override
implicitcasting to and from string so you don’t even need to see that you are talking to aSortOfMutableString.Refer to Jon Skeet’s answer for undoubtedly a very accurate explanation about string’s in C#, I’m not even going to bother!
Alternative class names: