Why string is immutable
chayan
About the type of C# String is value types or referenced types, maybe we always have some different thought.Example:
?static void StrChange(ref string str) //transfer the refrenced
so static void StrChange(string str) that the value is transfered, after we changed it in this function, the variable and out variable point same memory, so that's referenced of transfering , but when we changed the value in this function, it will be assigned new memory to save the value.
So the types of String is referenced , and the value is immutable. when we change it(ToUpper(),toLower() etc..),in fact it will create a new string,That's also why don't use string when we link too big char,we used StringBuilder.
To answer your query Chayan, let us have a look at the following code:
string str="123";
System.Console.WriteLine(str);
str +="456";
Strings are immutable in .NET means that you cannot change the value of a string once it is assigned. Although if you run the above code, the output would suggest that you've just changed the value of str to 123456 from 123, it is not so. Actually, in the first line, a new string object is allocated on the heap, with 123 as its value, and str points to its memory location. In the third line, another string object is allocated to the heap with 123456 as its value, and str now points to this location. So there are, in reality, two string objects in the heap, and only one of them is being referenced at the time. The 123 string is interned, and it is garbage collected if not used for a long time. So if you have several string objects, all with the value of "abc", they will all be referencing the same memory location. Now, if the strings would be mutable, and if you would change the content of any one string, you would be changing the value of all other strings which are pointing to it. Hence, the answer to your question, the reason of immutability. :)
In string If we create any number of string objects, all with same value they would all point to the same instance.If declare two strings like thisstring str1="1234"andstring str2="1234"
the above two strings points to the same string object.Now lets suppose if we can change the contents of the string str1as str1="12345" then str2 string's value will also change to "12345" which is not the right behaviour.
If we want the original string value to be modifiable then we can use stringbuilder
String takes new physical memory if you edit it. Where as Stingbuilder modify the same memory location
Why string is immutable . what happend in case of string in CLR . What is the difference from StringBuilder?