C# Language Nullable types

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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>


Got any C# Language Question?