tags:

views:

158

answers:

4

Should "" be assigned to a string to make it empty?

Or should it be a left as null?

+6  A: 

You can use either, but the canonical way is to assign it the value

string.Empty
Robert Harvey
+6  A: 

IMHO, the best approach is to assign it as String.Empty if you want it to be an empty string (and not null).

RobS
+1  A: 

Depends on what you're going to do with the string. If you set it to "", it's a valid object, and won't cause null reference exceptions when you pass it to some function that's expecting a string. But you also lose the ability to do a (quick) "if (str == null)", and the runtime ends up calling a function to do a string compare instead.

cHao
You could still test with String.IsNullOrEmpty(str) though....
klabranche
Yeah, but that involves another function call. Ideally you should be able to see whether your string contains a value by seeing if it's not null, *without* needing a function call.
cHao
True @cHao but can you control/guarantee whether your string is empty or null? Often you can't if it's input from something/somewhere else.... In this case, I would go for defensive code. Unless, of course, null and empty string meant something different in the code. :-)
klabranche
If it's my string, i can guarantee whatever i want to about it. :) And empty and null *do* mean different things. One means "i have a value, but it's blank", and the other means "i don't have a value". That the two are treated as the same thing is kinda depressing.
cHao
+4  A: 

It depends on the context. Frequently you'd leave the string null if you are simply going to assign to it. If you are using it in a context where you are going to perform additional actions on it that would fail if the reference was null and don't want to perform checks to see if it is null first, then an empty string might be better. I'll often do this if I'm getting a string parameter and want to extract something from it.

public string Foo( string bar )
{
    bar = bar ?? string.Empty;

    return bar.ToLower();
}

On the other hand, if the empty string would be a legal value and you need to differentiate an invalid action from the empty string as a legal value, then you may want to leave it null.

public string Foo( string bar )
{
    return bar == null ? null : bar.ToLower();
}
tvanfosson
That last line should be return bar == null ? null : bar.ToLower();
Eric Mickelsen
+1 for being absolutely correct (*"it depends"*), but -1 for not making the methods static when they do not reference `this`. (Just kidding, you still get a +1.)
Mark Rushakoff
@tehMick - thanks for the edit. That's what I get for not wearing my glasses. Getting old is a real pain, but it beats the alternative.
tvanfosson
@Mark -- I took out the `...` before I saved it. I'd actually never write either of these methods as they are. ;-)
tvanfosson
@tvanfosson - The alternative? Getting younger right???!!!!
klabranche
@klabranche -- tried that, but it embarassed my kids.
tvanfosson