I and friend of mine were discussing about strings in Dotnet framework, how they are reference type but act like value type (immutable). We both knew that strings are internal to CLR, but we did not really come to conclusion in that short discussion, how really strings are created and managed by CLR/Framework.
For example, in the below code clearly the s1
and s2
are different instances, but as you can see when I did s2.ToUpper()
the result refer back to the s1
.
public static void Main (string[] args)
{
string s1 = "HELLO";
string s2 = "hello";
Console.WriteLine (s1.GetHashCode()); //Prints 68624562
Console.WriteLine (s2.GetHashCode()); //Prints 99162322
Console.WriteLine (s2.ToUpper().GetHashCode()); //Prints 68624562 too!
}
So, the questions is on calling s2.ToUpper()
did CLR created new string "HELLO"
and check it already existed, if so then throw away newly created string? Can someone explain the magic here?