In C#, I want to initialize a string value with an empty string.
How should I do this? What is the right way, and why?
string willi = string.Empty;
I performed this very simple test using following method in a console application:
private static void CompareStringConstants()
{
string str1 = "";
string str2 = string.Empty;
string str3 = String.Empty;
Console.WriteLine(object.ReferenceEquals(str1, str2)); //prints True
Console.WriteLine(object.ReferenceEquals(str2, str3)); //prints True
}
This clearly suggests that all three variables namely str1
, str2
and str3
though being initialized using different syntax are pointing to the exactly same string (of zero length) object in memory . I performed this test in .NET 4.5 console application. So internally they have no difference and it all boils down to convenience of which one you want to use as a programmer. This behavior of string class is known as string interning in .NET. Eric Lippert has a very nice blog here describing this concept.