Why they say String object is immutable.
Printable View
Why they say String object is immutable.
not totally sure but i think they mean that a string cant be "changed"..if u have a string:
then myString will be pointing to "hi"Code:string myString = "hi";
then u make
then now will be created a new string saying "bye" and myString will be pointed to that..but actually the "hi" wasnt changed..i think it is that..Code:myString = "bye";
Who said so ? Can you provide any example shows that ?Quote:
Originally posted by vijayanand
Why they say String object is immutable.
it means if u change a string variable the CLR will create a new string object on the heap behind the scene.
foe example, the following will create new string intance on the heap:
String s = "a";
now, the following will create a new instance that s will point to it, but the former (contains "a") still remain in the heap until GC:
s = "b";
consider the following code:
String s = "a";
String s1 = s;
s = "b";
Console.WriteLine("s = " + s);
Console.WriteLine("s1 = " + s1);
the output will be:
s = b
s1 = a
String is a reference type, residing on the heap. in the above case we would assume that s and s1 are pointing to the same string because those variables are references to the same object (string) on the heap. but the result proving the opposite. the statement:
s1 = s;
actually point s1 to the string referenced by s, but when u change s:
s = "b";
CLR create new string and set the reference of s to it, but s1 still pointing to the old one.
String r very odd animal in the .NET framework, it is actually reference type but u don't have to use the New keyword to instanciate it as u would do in other reference types.
so, u must be careful when dealing with strings becuase it can degrade performance in some cases.
consider the following code:
String s;
for (int i = 0; i < 1000; i++)
s = i.ToString();
that code will create 999 string objects on the heap, it is huge waste of memory but many developers doesn't aware of this.
so, if u have to manipulate string very much times consider to use StringBuilder class (in System.Text namespace). that class are mutable and accepting changes without creating new obejcts.
the reason that String are immutable are performance issues. it is also sealed (means u can't derived from it) because the CLR have an internal knowledge of the String class, and can handle it very well.
just put the mouse up of System.String and see the intelsense :rolleyes:Quote:
Originally posted by Pirate
Who said so ? Can you provide any example shows that ?
lol , it's not of much help . I'm still unable to get it though ..lolQuote:
Originally posted by PT Exorcist
just put the mouse up of System.String and see the intelsense :rolleyes: