Checking to See Whether a String is Null or Empty

An empty string and a null string are two different things.  In some cases, you’ll want to check to see whether a string is null or to see whether it is non-null yet empty.
1
2
3
4
5
6
7
8
9
10
11
string bobsNickname = "Bubba";
string sallysNickname = "";
string joesNickname = null;
 
// Check for empty
if (sallysNickname == <span class="skimlinks-unlinked">string.Empty</span>)
    Console.WriteLine("No nickname for Sally");
 
// Check for null
if (joesNickname == null)
    Console.WriteLine("Joes nick is null");
Note that if we’d checked sallysNickname for null, the result would have been false.  Similarly, checking joesNickname for equality with string.Empty would also return false.
You can check for either null or empty in a single statement, using the IsNullOrEmpty method.
1
2
if (string.IsNullOrEmpty(sallysNickname))
    Console.WriteLine("No nick that we can use");