#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.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: