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

前端 未结 30 2342
挽巷
挽巷 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:44

    The compiler should make them all the same in the long run. Pick a standard so that your code will be easy to read, and stick with it.

    0 讨论(0)
  • 2020-11-22 02:44

    I was just looking at some code and this question popped into my mind which I had read some time before. This is certainly a question of readability.

    Consider the following C# code...

    (customer == null) ? "" : customer.Name
    

    vs

    (customer == null) ? string.empty : customer.Name
    

    I personally find the latter less ambiguous and easier to read.

    As pointed out by others the actual differences are negligible.

    0 讨论(0)
  • 2020-11-22 02:45

    One difference is that if you use a switch-case syntax, you can't write case string.Empty: because it's not a constant. You get a Compilation error : A constant value is expected

    Look at this link for more info: string-empty-versus-empty-quotes

    0 讨论(0)
  • 2020-11-22 02:45

    I'd prefer string to String. choosing string.Empty over "" is a matter of choosing one and sticking with it. Advantage of using string.Empty is it is very obvious what you mean, and you don't accidentally copy over non-printable characters like "\x003" in your "".

    0 讨论(0)
  • 2020-11-22 02:45

    Either of the first two would be acceptable to me. I would avoid the last one because it is relatively easy to introduce a bug by putting a space between the quotes. This particular bug would be difficult to find by observation. Assuming no typos, all are semantically equivalent.

    [EDIT]

    Also, you might want to always use either string or String for consistency, but that's just me.

    0 讨论(0)
  • 2020-11-22 02:47

    On http://blogs.msdn.com/b/brada/archive/2003/04/22/49997.aspx :

    As David implies, there difference between String.Empty and "" are pretty small, but there is a difference. "" actually creates an object, it will likely be pulled out of the string intern pool, but still... while String.Empty creates no object... so if you are really looking for ultimately in memory efficiency, I suggest String.Empty. However, you should keep in mind the difference is so trival you will like never see it in your code...
    As for System.String.Empty or string.Empty or String.Empty... my care level is low ;-)

    0 讨论(0)
提交回复
热议问题