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

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

    I have personally witnessed "" resulting in (minor) problems twice. Once was due to a mistake of a junior developer new to team-based programming, and the other was a simple typo, but the fact is using string.Empty would have avoided both issues.

    Yes, this is very much a judgement call, but when a language gives you multiple ways to do things, I tend to lean toward the one that has the most compiler oversight and strongest compile-time enforcement. That is not "". It's all about expressing specific intent.

    If you type string.EMpty or Strng.Empty, the compiler lets you know you did it wrong. Immediately. It simply will not compile. As a developer you are citing specific intent that the compiler (or another developer) cannot in any way misinterpret, and when you do it wrong, you can't create a bug.

    If you type " " when you mean "" or vice-versa, the compiler happily does what you told it to do. Another developer may or may not be able to glean your specific intent. Bug created.

    Long before string.Empty was a thing I've used a standard library that defined the EMPTY_STRING constant. We still use that constant in case statements where string.Empty is not allowed.

    Whenever possible, put the compiler to work for you, and eliminate the possibility of human error, no matter how small. IMO, this trumps "readability" as others have cited.

    Specificity and compile time enforcement. It's what's for dinner.

提交回复
热议问题