Why are the 2 string references the same? I am trying to write a copy constructor and want to avoid string references that point to the same string.
using System;
namespace StringRefTest
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("String Test!");
string s = "f"; // This should be one reference
string t = "f"; // This should be another
if (ReferenceEquals(s, t))
Console.WriteLine("Ref Same");
else
Console.WriteLine("Ref Not Same"); // Should be true
// The references are the same
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
Contrary to what others said, this behavior is not due to string interning. The compiled assembly’s metadata contain a table of string constants used. And the C# compiler is smart enough to notice those two strings are the same and use the same constant for both. If the compiler didn’t notice this, string interning would be what makes the difference.
To demonstrate this, I tried running a simple program with and without interning. According to CLR via C#, you can specify the
[CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)]attribute on an assembly to suggest turning off string inlining. The C# compiler always emits this attribute, but the CLR v.4.0 honors it only when using ngen. This comes in handy for us:This proves that string interning is not required for two string constants with the same value to be reference equal.