Default string initialization: NULL or Empty? [closed]
I have always initialized my strings to NULL, with the thinking that NULL means the absence of a value and "" or String.Empty is a valid value. I have seen more examples lately of code where String.Empty is considered the default value or represents no value. This strikes me as odd, with the newly added nullable types in c# it seems like we are taking strides backwards with strings by not using the NULL to represent 'No Value'.
What do you use as the default initializer and why?
Edit: Based on the answers I futher my further thoughts
-
Avoiding error handling If the value shouldn't be null, why did it get set to
NULL
in the first place? Perhaps it would be better to identify the error at the place where it occurs rather than cover it up through out the rest of your codebase? -
Avoiding null checks If you are tired of doing null checks in code, wouldn't it be better to abstract the null checks? Perhaps wrap (or extend!) the string methods to make them
NULL
safe? What happens if you constantly useString.Empty
and a null happens to work it's way into your system, do you start addingNULL
checks anyways?
I can't help but return to the opinion that it is laziness. Any DBA would slap you nine ways to silly if you used '' instead of null
in his\her database. I think the same principles apply in programming and there should be somebody to smack those upside the head who use String.Empty
rather than NULL
to represent no value.
Related Questions
- In C#, should I use string.Empty or String.Empty or “” ?
- What is the difference between String.Empty and “”
- Null or empty string to represent no data in table column?
+1 for distinguishing between "empty" and NULL. I agree that "empty" should mean "valid, but blank" and "NULL" should mean "invalid."
So I'd answer your question like this:
empty when I want a valid default value that may or may not be changed, for example, a user's middle name.
NULL when it is an error if the ensuing code does not set the value explicitly.
According to MSDN:
By initializing strings with the
Empty
value instead ofnull
, you can reduce the chances of aNullReferenceException
occurring.
Always using IsNullOrEmpty()
is good practice nevertheless.