You can read right in String.Empty, the value of this field (String.Empty
) is the zero-length string, ""
.
You can test that they refer to the same string with a small test.
void main()
{
String first = "";
String second = String.empty;
bool test = Object.ReferenceEquals(first, second);
}
Test will return true which means they refer to the same object.
Another slight difference is that evaluating ""
is slightly more optimal and efficient than String.empty
.
EDIT:
static void Main ( string[] args )
{
string s1 = "MyTest";
string s2 = new StringBuilder().Append("My").Append("Test").ToString();
string s3 = String.Intern(s2);
Console.WriteLine((Object)s2 == (Object)s1); // Different references.
Console.WriteLine((Object)s3 == (Object)s1); // The same reference.
Console.WriteLine();
s1 = "";
s2 = new StringBuilder().Append("").ToString();
s3 = String.Empty;
string s4 = String.Intern(s2);
Console.WriteLine((Object)s2 == (Object)s1); // The same reference.
Console.WriteLine((Object)s3 == (Object)s1); // The same reference.
Console.WriteLine((Object)s4 == (Object)s1); // The same reference.
Console.WriteLine((Object)s4 == (Object)s2); // The same reference.
}
It is quite obvious to tell with interning that a string literal is already interned. When stringbuilder
creates a new String object, that has the same object, it isn't interned and the references to the object are not the same. However, when we String.Intern(s2)
the method returns the same reference that is assigned to s1
and the reference is then assigned to s3
.
Thought
Why then, do all the four cases return true. I know the string literal ""
is interned, but why isn't using Stringbuilder
to append ""
to a new string object the same as ""
even though technically it is a new object that is not interned.