Type int? vs type int

Nullable types have special "boxing" rules; "boxing" is when a value-type is treated as object, as per your code. Unlike regular value-types, a nullable value-type is boxed either as null (regular null, no type), or as the non-nullable type (the T in T?). So: an int? is boxed as an int, not an int?. Then when you use OfType<int>() on it, you get all the values that are int, which is: the single value you passed in, since it is of type int.


A nullable value type is boxed by the following rules

  • If HasValue returns false, the null reference is produced.
  • If HasValue returns true, a value of the underlying value type T is boxed, not the instance of nullable.

In your example second rule has been followed as you have value:

var i = (object)(int?)123;

Tags:

C#

Casting