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

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

2 Responses to #208 – You Can Make Any Value Type Nullable

  1. Pingback: #776 – Declaring and Using Nullable structs « 2,000 Things You Should Know About C#

  2. kai zhou says:

    Good job. Sean.

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: