Should "" be assigned to a string to make it empty?
Or should it be a left as null?
Should "" be assigned to a string to make it empty?
Or should it be a left as null?
You can use either, but the canonical way is to assign it the value
string.Empty
IMHO, the best approach is to assign it as String.Empty if you want it to be an empty string (and not null).
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.
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();
}