#209 – Why You’d Want to Store a Null Value in a Variable

The Nullable<T> type lets us make any value type nullable.  But why is this useful?  When might we want to store a null value in a type, in addition to the normal range of values?

It’s often useful to represent the fact that a variable doesn’t have a value.

For example, assume that we have a class that stores some information about a book that we have read.  We might have a DateStarted and a DateFinished field:

            DateTime DateStarted;
            DateTime DateFinished;

If we want to be able to store information representing a book that has been started, but not yet finished, we’d want to store a value for DateStarted, but no value for DateFinished.  With a normal DateTime value, we couldn’t do this.  Instead, we make both fields nullable, allowing us to store a null value for either.

            DateTime? DateStarted;
            DateTime? DateFinished;

#208 – You Can Make Any Value Type Nullable

The ? character that indicates a nullable type is really a shortcut to the System.Nullable<T> structure, where T is the type being made nullable.  In other words, using int? is equivalent to using System.Nullable<System.Int32>.

You can make any value type nullable using the Nullable<T> syntax.  You’d typically do this for your own custom struct or enum types.

For example, assume that you have the following two custom types.

        // How I'm feeling
        public enum Mood
        {
            Crabby,
            Happy,
            Petulant,
            Elated
        }

        // A 3D point with a name
        public struct Point3D
        {
            public float X, Y, Z;
            public string Name;
        }

You can use these types as nullable types using Nullable<T>.

            Nullable<Mood> me = Mood.Crabby;
            me = null;

            Nullable<Point3D> nonPoint = null;