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;
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.
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.
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
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 ""
.
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.
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... whileString.Empty
creates no object... so if you are really looking for ultimately in memory efficiency, I suggestString.Empty
. However, you should keep in mind the difference is so trival you will like never see it in your code...
As forSystem.String.Empty
orstring.Empty
orString.Empty
... my care level is low ;-)