I guess it has to do something with string being a reference type but I dont get why simply string.Replace("X","Y")
does not work?
Why do I need to do string A = stringB.Replace("X","Y")
? I thought it is just a method to be done on specified instance.
EDIT: Thank you so far. I extend my question: Why does b+="FFF"
work but b.Replace
does not?
String.Replace is a shared function of string class that returns a new string. It is not an operator on the current object. b.Replace("a","b") would be similar to a line that only has c+1. So just like c=c+1 actually sets the value of c+1 to c, b=b.Replace("a","b") sets the new string returned to b.
As everyone above had said, strings are immutable.
This means that when you do your replace, you get a new string, rather than changing the existing string.
If you don't store this new string in a variable (such as in the variable that it was declared as) your new string won't be saved anywhere.
Just to be more explicit. string.Replace("X","Y") returns a new string...but since you are not assigning the new string to anything the new string is lost.
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:Emphasis mine.
Good question.
First note that
b += "FFF";
is equivalent tob = 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 tob
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.A StringBuilder supports the inline Replace method.
Use the StringBuilder if you need to do a lot of string manipulation.
Strings are immutable. Any operation changing them has to create a new string.