#216 – Null-Coalescing (??) Operator Is Equivalent to GetValueOrDefault Method

The Nullable<T> type has a GetValueOrDefault(T) method that behaves in a way identical to the ?? operator.  It returns the value of the object, if non-null, or the value of the parameter passed in if the object is null.

            Nullable<Mood> myMood = null;

            Mood mood2 = myMood ?? Mood.Happy;   // result = Happy, since myMood is null
            Mood mood3 = myMood.GetValueOrDefault(Mood.Happy);   // same as above

There is also an overload of the GetValueOrDefault method that doesn’t take a parameter but just returns the default value for the type T, if the object in question is null.  For example, an enum type has a default value of 0, so the enumerated constant equivalent to 0 is returned.

        public enum Mood
        {
            Crabby,   // 0-valued
            Happy,
            Petulant,
            Elated
        }
            Nullable<Mood> myMood = null;

            Mood mood2 = myMood.GetValueOrDefault();   // Gets value Mood.Crabby
Advertisements

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

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 )

Google+ photo

You are commenting using your Google+ 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: