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

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

One Response to #206 – Value Types Can’t Represent Null Values

  1. Pingback: #207 – Nullable Types « 2,000 Things You Should Know About C#

Leave a comment