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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.