I want to know which is the preferred way to declare a string in C#:
string strEmpty = String.Empty;
or
string strNull = null;
Which practice is better or what is the difference between these statements.
I want to know which is the preferred way to declare a string in C#:
string strEmpty = String.Empty;
or
string strNull = null;
Which practice is better or what is the difference between these statements.
the first answer makes the value of the string an actual empty string. Assigning it to null makes the pointer point to nothing. This means that if you tried to do strEmpty.Function(), it wouldn't work in the second case.
The first takes more memory initially, but is more clear.
The correct answer depends on what you would do next. If you are just going to reassign the string, I would make it null
. If you intend to do stuff to the string (execute functions, append, etc), I would make it string.empty
.
There is no "best". What you do depends on what you mean.
An empty string has a length of 0, but it is a string. Do this when you absolutely must return some kind of string, even if it's zero length. This is rare.
A null is not a string in the first place, it's a null pointer. Do this when the absence of a string is a meaningful condition that may influence other parts of the application.
The difference is semantical.
Whenever you find in the code a NULL pointer, it means that is truly nothing. It means it has not been initialized to anything, so you can't use it.
On the other hand, an empty string is a string. It's been initialized and any programmer looking at the code will consider that string as a valid object to be used.
Consider for example having a relative URL stored in a string. If you find that string empty, you'll think it's pointing to the root path. But if it's NULL, you should consider it's not a valid variable whatsoever - it's not been initialized and you should not use it.
Based on that, you'll take different paths - an empty URL means something very different from a NULL variable.
The difference between null and empty string is indeed semantic but they are largely equivalent by convention.
In .NET the System.String
class has a static method IsNullOrEmpty
that it is best practice to use in most cases.
In a typical line-of-business app, the semantic difference is very clear: Null means the value is unknown or not applicable, and Empty means the value is known to be blank.
In other types of app, the semantics are more or less up to you, as long as you document them and apply them consistently across your whole team.
There is no difference in performance.