Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which should I use for empty string and why? [duplicate]

Tags:

string

c#

.net

Possible Duplicate:
What is the difference between String.Empty and “”

Which of the following should I use for assigning an empty string and why?

string variableName = "";

or

string variableName = string.Empty;
like image 800
Prabhanjan Naib Avatar asked Jul 07 '10 06:07

Prabhanjan Naib


2 Answers

String.Empty is what is normally recommended.

Why? Because it conveys meaning, you are very explicitly saying that you want the string to be empty.

Additionally, "" creates a string object (this object will be reused across the applications, because strings in .NET are interned), String.Empty does not create a new object. See here.

like image 102
Oded Avatar answered Nov 15 '22 09:11

Oded


Use whatever your project or team style guidelines say. And if you have none, just chat about it for a moment, choose one and use it consistently.

Technically both are identical and lead to the same code. String.Empty represents instance of interned empty string (""). And since all in-code string constants are automatically interned, "" represents exactly the same instance of empty string (Update: Within assembly, see update below).


And by the way, I'm using "". It's short, clear and readable.

String.Empty is useful in generic code using reflection etc. When you don't care what class you have, just want to get empty value for e.g. initialization with default value.


Update: It appears that it's not that simple. There might be many instances of interned string within single app domain. And the behavior depends on framework version. For more information see Eric Lippert's String interning and String.Empty and remarks in Reference for String.Intern method.

But the second link suggest that since 3.5 SP1 there is again single interned "", as it should be in the first place. So, why bother with it when you program? Projects take some time to complete. Factor in improvements in compilers, frameworks and tools... And don't optimize prematurely. It's more important to be readable, consistent and correct.

like image 38
Tomek Szpakowicz Avatar answered Nov 15 '22 07:11

Tomek Szpakowicz