Why doesn't stringA.Replace("X","Y")
work?
Why do I need to do stringB = stringA.Replace("X","Y");
?
Because strings are immutable in .NET. You cannot change the value of an existing string object, you can only create new strings. string.Replace
creates a new string which you can then assign to something if you wish to keep a reference to it. From the documentation:
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
Emphasis mine.
So if strings are immutable, why does b += "FFF"; work?
Good question.
First note that b += "FFF";
is equivalent to b = b + "FFF";
(except that b is only evaluated once).
The expression b + "FFF"
creates a new string with the correct result without modifying the old string. The reference to the new string is then assigned to b
replacing the reference to the old string. If there are no other references to the old string then it will become eligible for garbage collection.