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

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

    I wasn't going to chime in, but I'm seeing some wrong info getting tossed out here.

    I, personally, prefer string.Empty. That's a personal preference, and I bend to the will of whatever team I work with on a case-by-case basis.

    As some others have mentioned, there is no difference at all between string.Empty and String.Empty.

    Additionally, and this is a little known fact, using "" is perfectly acceptable. Every instance of "" will, in other environments, create an object. However, .NET interns its strings, so future instances will pull the same immutable string from the intern pool, and any performance hit will be negligible. Source: Brad Abrams.

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

    No one mentioned that in VisualStudio String is color coded differently then string. Which is important for readability. Also, lower case is usually used for vars and type, not a big deal but String.Empty is a constant and not a var or type.

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

    I doesn't make a difference. The last one is the quickest to type though :)

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

    It doesn't matter - they are exactly the same thing. However, the main thing is that you must be consistent

    p.s. I struggle with this sort of "whats the right thing" all the time.

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

    I personally prefer "" unless there is a good reason to something more complex.

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

    This topic is pretty old and long, so excuse me if this behavior has been mentioned somewhere else. (And point me to the answer that covers this)

    I have found a difference in the behavior of the compiler if you use string.Empty or double quotes. The difference shows itself if you don't use the string variable initialized with string.Empty or with double quotes.

    In case of initialization with string.Empty then the Compiler Warning

    CS0219 - The variable 'x' is assigned but its value is never used
    

    is never emitted while in case of initialization with double quotes you get the expected message.

    This behavior is explained in the Connect article at this link: https://connect.microsoft.com/VisualStudio/feedback/details/799810/c-warning-cs0219-not-reported-when-assign-non-constant-value

    Basically, if I get it right, they want to allow a programmer to set a variable with the return value of a function for debugging purposes without bothering him with a warning message and thus they limited the warning only in case of costant assignments and string.Empty is not a constant but a field.

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