#1,010 – 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.

            string bobsNickname = "Bubba";
            string sallysNickname = "";
            string joesNickname = null;

            // Check for empty
            if (sallysNickname == string.Empty)
                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.

            if (string.IsNullOrEmpty(sallysNickname))
                Console.WriteLine("No nick that we can use");