Hello everyone,
I read from some documents that string/array are immutable, means when we change the content of a string (e.g. append text) or change the content of an array (e.g. append new element), then a new instance be created and the old instance will be discarded?
thanks in advance,
George
Rasik Bihari TiwariPosted Feb 18, 2017, 7:56 AM
George GeorgePosted Aug 26, 2008, 10:05 PM
Thanks Ryan, question answered.
regards,
George
Ryan AlfordPosted Aug 26, 2008, 11:03 AM
yes, strings are immutable. you never actually modify the string variable after it's initial instantiation. The part that you are wrong is the "the old instances will be discarded". The old instances will stay in memory.
example:
string value = string.Empty;
value += "hey";
value += "there;
value += "how";
value += "are";
value += "you";
value += "doing";
in memory, you have now created 7 seperate variables. these instances will stay in memory. because of this, you are recommended to use the StringBuilder object when appending to a string.
George GeorgePosted Aug 25, 2008, 8:53 AM
Thanks Niradhip,
In your case, then the content of the string pointed by str1 changes, I think the underlying operation is, there is a new instance created to reflect the new string content and str1 will be binded to the new string, and str2 still binded to the old string, correct?
regards,
George
Niradhip ChakrabortyPosted Aug 25, 2008, 8:27 AM
String str1 = “xyz”;
String str2 = “xyz”;
Now compiler will check in String Pool where there is same characters are available or not. If two Strings are match the compiler will refer str1 address to str2. Now the str1 and str2 referring the same characters in same memory location. This is a good idea for increasing memory efficiency.
When we change the str1 characters, the changes will be reflected to str2. Because both str1 and str2 variables are referring the same memory location. For avoiding this we are keeping String as immutable. However we can use StringBuffer if you want to do modifications in the string.
George GeorgePosted Aug 25, 2008, 7:35 AM
Thanks Niradhip!
1.
What means pool format?
2.
I think for array, we can not change its content (e.g. when change some specific char inside a string, a new instance will be created), correct?
regards,
George
Niradhip ChakrabortyPosted Aug 25, 2008, 6:37 AM
String in a class it is used to holding the array of characters.String is immutable. Means we can not change the value of the string.
Strings are handling in Pool format.
For example:
String str1 = “xyz”;
This string(str1) will be stored into memory in particular address.
Check Out the following articles:
1. http://www.braintique.com/csharp/chapters/03ch01.shtml
2.http://blogs.msdn.com/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx