Strings and Nulls in C#

A very common thing in coding is to want to see if you’ve been given a string or not.

 

In C#, a string is a reference to an object, and this reference can be null, or it can be a reference to a string, which can contain 0 or more characters.

 

When you want to see if you have a string or not, you need to first check to see if it’s a null reference, and if it’s not, then see if the string contains any characters.  This ends up looking something like:

 

  if (firstName != null && firstName.Length > 0)

  {

    // do something with firstName 

  }

 

If I’m calling a function that doesn’t require a first name, I can pass in a null.  The disconnect is that if I’m, say, reading data from a text file and the file has a place where the name is going to be, the empty case for the string is simply going to be a string with no characters.

 

So someone has to say ‘this string with no characters is really a null’, or everywhere you access the string, you need to see if it’s null.

 

I don’t have any great insight to offer here; I just find it less than elegant.  I’d like a way to test to see if a string is both non-null and non-empty without having to do the two separate comparisons.