#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