#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");
Advertisements

#1,009 – A String Can Be Null or Empty

string variable can refer to a string that either contains characters, or an empty string.  Because string is a reference type, a variable of type string can also be assigned a value of null, indicating that the variable does not refer to any string.

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

There is a difference between an empty string and a null string.  A variable that is set to an empty string refers to a location in memory containing a string that has no characters.  A string variable set to null refers to nothing.

You can choose to use empty strings in your code to mean one thing and nulls to mean something different.  In the code above, it might be the case that Sally explicitly does not have a nickname, whereas we just haven’t yet figured out what Joe’s nickname is.