In C#, should I use string.Empty or String.Empty or “” to intitialize a string?

前端 未结 30 2563
挽巷
挽巷 2020-11-22 02:06

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;
         


        
30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 02:33

    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.

提交回复
热议问题