Hi Jon,
Your example code has been bothering me - it should work, however it
doesn't and I can't figure out why
But if you think that's weird, check out the following documentation I
found on MSDN:
"String.Intern Method"
http://msdn2.microsoft.com/en-us/library/system.string.intern.aspx
<quote>
Version Considerations
Starting with the .NET Framework version 2.0, there is a behavioral change
in the Intern method. In the following C# code sequence, the variable str1
is assigned a reference to Empty, the variable str2 is assigned the
reference to Empty that is returned by the Intern method, then the
references contained in str1 and str2 are compared for equality.
string str1 = String.Empty;
string str2 = String.Intern(String.Empty);
if ((object) str1) == ((object) str2) .
In the .NET Framework version 1.1, str1 and str2 are not equal, but
starting in the .NET Framework version 2.0, str1 and str2 are equal.
</quote>
Not in my test :|
string str1 = String.Empty;
string str2 = String.Intern(String.Empty);
// false
Console.WriteLine((object) str1 == (object) str2);
// false
Console.WriteLine((object) string.Empty == (object) "");
// true
Console.WriteLine((object) "" == (object) "");
Using Reflector I verified that string.Empty is assigned the empty
literal, "", in the class constructor (.cctor). I also verified, through
testing, that interning works across assemblies; so I'm stumped here.
The earliest version of the framework that I have installed on my machine
is 2.0, verified in Add or Remove Programs. I also have 3.0 installed, if
that makes a difference.
Anyone know what's going on here?
--
Dave Sexton
Jon Shemitz said:
Morten said:
"" is easy to write, easy to read, and near impossible to misunderstand.
It will however create an object where String.Empty would not, but the
""
object is reused throughout the lifespawn of your application so the
difference can therefore be ignored.
I was surprised to read that "" will create an object where
String.Empty will not - surely String.Empty is just a static field
that points to an interned "" constant?
Sure enough, Reflector shows that String.Empty is implemented as
class string
{
static readonly string Empty = "";
}
... yet the below code shows that while both "" and String.Empty are
interned, "" is not reference-equal to String.Empty. What gives? I
thought the intern table was maintained across assembly boundaries, so
it shouldn't matter that String.Empty comes from mscorlib.dll while ""
comes from the app assembly.
//
using System;
namespace StringEmptyTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Object.ReferenceEquals(String.Empty, ""));
Console.WriteLine(String.IsInterned("") != null);
Console.WriteLine(String.IsInterned(String.Empty) != null);
Console.ReadLine();
}
}
}
--
.NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.