Search code examples
c#intvalue-typereference-type

Is int? a value type or a reference type?


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.


Solution

  • 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)