I've seen similar questions and answers but I couldn't find the one I'm thinking of. How is this possible that CLR somehow knows which string is the same and which is not and makes the same object if I write down the same string value but no show it the object explicitly?
class Program
{
static void Main()
{
String test = "test";
String test2 = "test";
String test3 = test;
String test4 = String.Copy(test);
Console.WriteLine(Object.ReferenceEquals(test, test2));
Console.WriteLine(Object.ReferenceEquals(test, test3));
Console.WriteLine(Object.ReferenceEquals(test, test4));
Console.ReadLine();
}
}
The output of this code will be:
True
True
False
Why is it allocating strings "test" and "test2" in the same place? If the string would be "dsfadsfdsafdasfsadfasfdagfgfafadsf" or even longer, I wonder is it efficient to compare all these strings or is it made in other way?