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?
The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.
To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.
You use the replace() method by: assigning the initial string or strings to a variable. declaring another variable. for the value of the new variable, prepending the new variable name with the replace() method.
Because strings are immutable. Any time you change a string .net creates creates a new string object. It's a property of the class.
Immutable objects
String Object
Why doesn't
stringA.Replace("X","Y")
work?
Why do I need to dostringB = 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.
Strings are immutable, which means that once they are created, they cannot be changed anymore. This has several reasons, as far as I know mainly for performance (how strings are represented in memory).
See also (among many):
As a direct consequence of that, each string operation creates a new string object. In particular, if you do things like
foreach (string msg in messages)
{
totalMessage = totalMessage + message;
totalMessage = totalMessage + "\n";
}
you actually create potentially dozens or hundreds of string objects. So, if you want to manipulate strings more sophisticatedly, follow GvS's hint and use the StringBuilder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With