#217 – T? Is Equivalent to Nullable<T>

You can always use the form T?, rather than Nullable<T>, to declare a variable whose type is a nullable value type.  The type T can be any built-in or custom value type.

This means that you can use this syntax for your own custom enum or struct types.

For example, if you have the following custom types:

        public enum Mood
        {
            Crabby,
            Happy,
            Petulant,
            Elated
        }

        public struct Point3D
        {
            public float X, Y, Z;
            public string Name;
            public Point3D(float x, float y, float z, string name)
            {
                X = x;
                Y = y;
                Z = z;
                Name = name;
            }
        }

You can use the T? format as follows:

            Mood? myMood = null;
            Mood mood2 = myMood ?? Mood.Elated;

            Point3D? somePoint = null;
            Point3D defaultPoint = new Point3D(0.0f, 0.0f, 0.0f, "Origin");
            Point3D aPoint = somePoint ?? defaultPoint;

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers