Nullability Revisited Briefly

During our discussion about nullable value types, introduced in .NET 2.0, we mentioned the syntactical sugar in C# to be an abbreviation for use of the Nullable<T> struct:

int? x = 42;Nullable<int> y = null;

Both the int? and Nullable<int> types in the preceding example are therefore the same. A few more things can be told about nullable types.

First of all, don’t forget the instance-level members available on any Nullable<T> object. C# conveniently provides a more natural syntax to express those constructs, but it’s good to know about their existence:

bool b = x.HasValue;              // Same as:     bool b = x == null;int c = y.GetValueOrDefault(25);  // Similar to:  int c = y ?? 25; ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.