From Richter and this discussion, I would expect any two "identical" strings to be the same reference. But just now in LINQPad I got mixed results on this topic. Here is the code:
void Main()
{
string alpha = String.Format("Hello{0}", 5);
string brava = String.Format("Hello{0}", 5);
ReferenceEquals(alpha, brava).Dump();
String.IsInterned(alpha).Dump();
String.IsInterned(brava).Dump();
alpha = "hello";
brava = "hello";
ReferenceEquals(alpha, brava).Dump();
}
And here are the results from the Dump() calls:
False
Hello5
Hello5
True
I would have expected both the first and last ReferenceEquals
to be True
. What happened?
Besides the example above, in what other cases would the ReferenceEquals fail? For example, multi-threading?
This issue is important if, for example, I'm using string parameters passed into a method as the object upon which a lock is taken. The references better be the same in that case!!!