This code snippet is from C# in Depth
static bool AreReferencesEqual<T>(T first, T second)
where T : class
{
return first == second;
}
static void Main()
{
string name = "Jon";
string intro1 = "My name is " + name;
string intro2 = "My name is " + name;
Console.WriteLine(intro1 == intro2);
Console.WriteLine(AreReferencesEqual(intro1, intro2));
}
The output of the above code snippet is
True
False
When the main method is changed to
static void Main()
{
string intro1 = "My name is Jon";
string intro2 = "My name is Jon";
Console.WriteLine(intro1 == intro2);
Console.WriteLine(AreReferencesEqual(intro1, intro2));
}
The output of the above code snippet is
True
True
I cannot fathom why ?
EDIT: Once you understand string-interning following questions don't apply.
How are the parameters received at the Generic method AreReferencesEqual
in the second code snippet ?
What changes to the string type when it is concatenated to make the == operator not call the overloaded Equals method of the String type ?