Stats

98 Contributors: 11 Monday, August 1, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Nullable types

Syntax

  • Nullable<int> i = 10;
  • int? j = 11;
  • int? k = null;
  • DateTime? DateOfBirth = DateTime.Now;
  • decimal? Amount = 1.0m;
  • bool? IsAvailable = true;
  • char? Letter = 'a';
  • (type)? variableName

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 object boxing, the null value is converted to null reference, and non-null value is converted to non-nullable underlying type.

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

DateTime? dt = new DateTime(2015, 12, 11);
var o = (object)dt;
var dt2 = (DateTime)dt; // correct cause o contains DateTime value

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>

Related Examples