Are nullable types reference types in .NET?

Usually you can't assign null to value types, such as int, bool, DateTime, etc. You can make them nullable by adding ? symbol after type declaration of variable/field/property:

int? nullableNumber = null;

But does nullableNumber become reference variable?

Nullable type are neither value type nor reference type. Nullable is a struct, but it has few differences from usual structs. The nullable struct has two properties:

  1. Property with the value of the data type (int for int?).
  2. A boolean property which tells if the data type value has been set (HasValue).

When you set the value nullable variable, the struct changes HasValue to true.

Since nullable type is a struct, it's definetly not a reference type. But since nullable can be assigned null value, a nullable type cannot satisfy a struct constraint in generics. Also, when you box a nullable type with HasValue equal to false, you get a null pointer instead of a boxed nullable type:

bool? b = null;
object o = b;
// Now o is null.

If the object is non-null (HasValue is true), then boxing occurs, but only the underlying type that the nullable object is based on is boxed. Boxing a non-null nullable value type boxes the value type itself, not the System.Nullable<T> that wraps the value type:

bool? b = false;
object bBoxed = b;
// bBoxed contains a boxed bool.

This makes nullable kind of it's own type with behavior different from both reference and value types.

Short answer

  • Nullable variable is a struct but with few differences: it has two properties and can't satisfy struct constraint in generics.
  • Nullable variable is not a reference type, although it can be assigned null.
  • Boxing a non-null nullable value type boxes the value type itself, not the System.Nullable<T> that wraps the value type.

Comments