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

#730 – Check for null Before Iterating Using foreach Statement

The foreach statement allows iterating through all items in a collection.

            List<string> dogs = new List<string>();
            dogs.Add("Kirby");
            dogs.Add("Jack");

            foreach (string s in dogs)
                Console.WriteLine(s);

            Console.WriteLine("=> Done");

730-001

If the collection referenced in the foreach statement is empty, the body of the loop does not execute.  No exception is thrown.

            List<string> dogs = new List<string>();

            foreach (string s in dogs)
                Console.WriteLine(s);

            Console.WriteLine("=> Done");

730-002
If the object that refers to the collection is null, a NullReferenceException is thrown.

            List<string> dogs = null;

            foreach (string s in dogs)
                Console.WriteLine(s);

            Console.WriteLine("=> Done");

730-003
Because of this, it’s good practice to check for null before iterating through a collection in a foreach loop.

            if (dogs != null)
                foreach (string s in dogs)
                    Console.WriteLine(s);

#588 – A Default Parameter Value Can Be Null

When defining optional parameters and providing a default value for the parameter, you can use a value of null for a reference-typed parameter.  null is actually the only valid default value that you can use for a reference-typed parameter.

        static void LogDogInfo(Dog myDog, Dog anotherDog = null)
        {
            Console.WriteLine("My dog is {0}", myDog.Name);
            if (anotherDog != null)
                Console.WriteLine("  And there is also {0}", anotherDog.Name);
        }

        static void Main()
        {
            Dog dog1 = new Dog("Kirby", 15);
            Dog dog2 = new Dog("Jack", 17);

            LogDogInfo(dog1);
            LogDogInfo(dog2, dog1);
        }

#477 – Full List of Escape Sequences for Character Literals

You can use one of several escape sequences within a character literal to represent a character that you can’t include directly in the literal.

The full list of character literals includes:

  • \’ – Single quote (U+0027)
  • \” – Double quote (U+0022)
  • \\ – Backslash (U+005C)
  • \a – Alert (U+0007)
  • \b – Backspace (U+0008)
  • \f – Form feed (U+000c)
  • \n – New line (U+000A)
  • \r – Carriage return (U+000D)
  • \t – Horizontal tab (U+0009)
  • \v – Vertical tab (U+000B)
            char single = '\'';
            char dquote = '\"';
            char backslash = '\\';
            char alert = '\a';
            char backspace = '\b';
            char formFeed = '\f';
            char newLine = '\n';
            char cr = '\r';
            char horizTab = '\t';
            char vertTab = '\v';

You can also use a backspace followed by 0 to indicate a null character.

            char nullChar = '\0';

#207 – Nullable Types

Because value types can’t normally represent null values, C# includes nullable types–types that can represent their normal range of values or represent a null value.

Any value type can be used as a nullable type by adding a trailing ? to the type name.

            int i = 12;   // regular int, can't be null

            int? j = 22;  // Nullable int, can be null
            j = null;     // Can also be null

Here are some other examples of nullable types.  In each case, we can set the variable’s value to null, which means that the variable doesn’t have a value that falls within the range of the corresponding type.

            double? r = null;
            bool? thisIsFalse = null;
            Mood? myMood = null;

#206 – Value Types Can’t Represent Null Values

A reference type variable can be set to point to an instance of the type that it represents, or it can be set to the null value.  The null value indicates that the object doesn’t point to anything.

            Person p = new Person("Eddie", "Cantor");    // Points to a person
            p = null;   // Now points to nothing

Value typed variables, on the other hand, must have a value that can be represented by the corresponding type.  They cannot contain a null value.

            int i = 12;   // ok
            i = null;     // Error: Non-nullable value type

You could store the value of 0 in this variable, but 0 typically means something different than a null value.  Generally, we think of a null value as meaning–the variable doesn’t contain a value.  It can often be useful to represent this fact, whether you’re using a reference typed variable or a value typed variable.