#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;
Advertisement

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

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

  1. kai zhou says:

    Thank you Sean.
    Sometimes because the corresponding field in database table is nullable, so we make the property of the class as nullable.

  2. Seraph says:

    this is a good idea!

    Hallo, Sean, I am reading your blog. It is a good tutorial… thanks a lot. Are you keeping writing it?

    • Sean says:

      Thanks Seraph. Unfortunately, the blog is on hiatus at the moment, given the extraordinary amount of time it takes to add new content.

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: