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?
To answer your extended question, b+="FFF" is equivalent to b = b + "FFF", so basically you are creating a new string here also.
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
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.
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
Yes its a method of System.String. But you can try a = a.Replace("X","Y");
Because the += operator assigns the results back to the left hand operand, of course. It's just a short hand for
b = b + "FFF";
.The simple fact is that you can't change any string in .Net. There are no instance methods for strings - you must always assign the results of an operating back to a string reference somewhere.