Is int? a value type or a reference type?

user2769119 picture user2769119 · Sep 11, 2013 · Viewed 7.3k times · Source

This question is more about adding a ? to a value type than about int?

In C# an int is a value type. Is int? a value type or a reference type?

In my opinion it should be a reference type as it can be null.

Answer

Soner Gönül picture Soner Gönül · Sep 11, 2013

int? is equivalent to Nullable<int> which means it is a struct.

So that means it is a value type.

In my opinion it should be a reference type as it can be null.

Your assumption is wrong. From documentation;

Nullable structure represents a value type that can be assigned null. The Nullable structure supports using only a value type as a nullable type because reference types are nullable by design.

So it has 2 values;

  1. The value of data
  2. Boolean value which determines the values has been set or not. (Nullable<T>.HasValue)