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.
1
2
3
4
| Nullable<Mood> myMood = null;Mood mood2 = myMood ?? Mood.Happy; // result = Happy, since myMood is nullMood 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.
1
2
3
4
5
6
7
| public enum Mood{ Crabby, // 0-valued Happy, Petulant, Elated} |
1
2
3
| Nullable<Mood> myMood = null;Mood mood2 = myMood.GetValueOrDefault(); // Gets value Mood.Crabby |

