Click here to Skip to main content
15,887,262 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
what is difference between mutable and immutable
Posted

In C#, all strings are immutable - which is a fancy way of saying "can't be changed" (mutable means it can be changed).
It may look as if you are changing a string but every time you perform an operation on a immutable object, it happens to a copy of the the string and a new string is returned.
For example:
C#
string s1 = "hello ";
string s2 = s1 + "there ";
string s3 = s2 + "Joe!";
Console.WriteLine(s1);
Console.WriteLine(s2);
Console.WriteLine(s3);

Because strings are immutable, creating s2 does not affect s1, and similarly creating s3 does not affect s2 or s1:
hello 
hello there 
hello there Joe!
Once you create a member of the string class, it will never be changed. A StringBuilder on the other hand is mutable - you can add and remove data from it, and it is only ever copied when the space allocated is too small to hold the new data.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900