This might sound like a noob question, but are:
string var;
if (var == null)
and
string var;
if (var == string.Empty)
The same?
Duplicate
What's the Difference between String.Empty and Null? and In C#, should I use String.Empty or Null?
This might sound like a noob question, but are:
string var;
if (var == null)
and
string var;
if (var == string.Empty)
The same?
Duplicate
What's the Difference between String.Empty and Null? and In C#, should I use String.Empty or Null?
@Jay is correct, they are not the same. String.IsNullOrEmpty()
is a convenient method to check for both null and "".
No, they are not the same.
string.Empty
is the same as ""
, which is an actual object: a string of 0 length. null
means there is no object.
they are not the same, the implementation of String.IsNullOrEmpty(string) in mscorlib demonstrate it:
public static bool IsNullOrEmpty(string value)
{
if (value != null)
{
return (value.Length == 0);
}
return true;
}
No, they are not. First one checks if the variable has been initialized or if it was set to "null" later. Second one checks if the value of the variable is "" (empty). However, you shouldn't use either. You should use string.IsNullOrEmpty(var) instead.
But sometimes you want to know if the string is NULL
and it does not matter that its empty (in a OO design). For example you have a method and it will return NULL
or a string.
you do this because null means the operation failed and an empty string means there is no result.
In some cases you want to know if it failed or if it has no result prior to take any further actions in other objects.