I have found code on a website which is as follows.
string a = "xx";
string b = "xx";
string c = "x";
string d = String.Intern(c + c);
Console.WriteLine((object)a == (object)b); // True
Console.WriteLine((object)a == (object)d); // True
Here, what is the purpose of casting into object type again since a,b,d are itself the objects of string?
The C# compiler will try to get all constant strings at compile time. This is called string interning. So after the code generated a
and b
are references to the same string which contains "xx".
You can check this by comparing their references (casting them to object and do the equality check or use object.ReferenceEquals
). Keep in mind that ==
operator for strings compare their values not their references.
Another thing to mention is that strings are immutable in .NET.
string a = "xx";
string b = "x" + "x"; // String interning here
string c = string.Join("", new[] { "x", "x" }); // No interning here because it is evaluated at runtime
Console.WriteLine((object)a == (object)b); // True. Reference check
Console.WriteLine(a == b); // True. Value check
Console.WriteLine((object)a == c); //False. Reference check. Described below
Console.WriteLine(a == c); // True. Value check
So why is Console.WriteLine((object)a == c);
doing a reference check?? Because the compiler will choose the ==
operator on object which checks for reference equality.
So the whole point of casting to object in your question is to check if string interning works or not. Assuming that there is no interning happen at compile time.
string a = "xx";
string b = "xx";
string c = "x";
string d = String.Intern(c + c);
Then Console.WriteLine((object)a == (object)b);
would print "False", because a
and b
are references for two different string in memory, both of which look like "xx".