Nullable types

suggest change

Syntax

Remarks

Nullable types can represent all the values of an underlying type as well as null.

The syntax T? is shorthand for Nullable<T>

Nullable values are System.ValueType objects actually, so they can be boxed and unboxed. Also, null value of a nullable object is not the same as null value of a reference object, it’s just a flag.

When a nullable value is boxed, a null value becomes a null reference, and a non-null value is boxed as the underlying type.

DateTime? dt = null;
var o = (object)dt;
var result = (o == null); // is true

DateTime? dt2 = new DateTime(2015, 12, 11);
var o2 = (object)dt2;
var unpacked = (DateTime)o2; // o2 is a boxed DateTime, not Nullable<DateTime>

The second rule leads to correct, but paradoxical code:

DateTime? dt = new DateTime(2015, 12, 11);
var o = (object)dt;
var type = o.GetType(); // is DateTime, not Nullable<DateTime>

In short form:

DateTime? dt = new DateTime(2015, 12, 11);
var type = dt.GetType(); // is DateTime, not Nullable<DateTime>

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents