5

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?

Community
  • 1
  • 1
Ash
  • 24,276
  • 34
  • 107
  • 152

5 Answers5

31

@Jay is correct, they are not the same. String.IsNullOrEmpty() is a convenient method to check for both null and "".

Jay Bazuzi
  • 45,157
  • 15
  • 111
  • 168
Kevin Tighe
  • 20,181
  • 4
  • 35
  • 36
19

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.

Jay Bazuzi
  • 45,157
  • 15
  • 111
  • 168
6

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;
}
3

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.

Ilya Volodin
  • 10,929
  • 2
  • 45
  • 48
0

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.

akjoshi
  • 15,374
  • 13
  • 103
  • 121
wiener
  • 1