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
.
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
.
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;
Nullable<T>.HasValue
)Nullable types are instances of the System.Nullable struct Hence int?
is a Value Type.
int?
is not a reference type. It is a struct
(value type).
It has its own value like a normal int plus an additional "null" value. With Nullable types, you can check if it has a value using HasValue
.
EDIT I should've started with this example in the 1st place:
Think about enums. Every enum we write automatically extends Enum
, which is a class.
Hence, value types we write extend a class written by the .NET team which is a reference type.
You can split the world of types in two ways:
null
value or notAll combinations are possible in theory. If I'm not mistaking, in C# at least, the combination of reference types which cannot be null
yields an empty set. There is no example for that combination.
Basically all other 3 combinations are possible:
The nature of being either a value type or a reference type has nothing to do with null
(at least in the way languages should be designed and used, not in the way of the actual engineering details underneath).
Value types are types which cause assignments between variables, parameters and fields to do full cloning of the instance. Reference types are types which don't do that.
That has basically nothing to do with null
or with the type of memory which is occupied by the instances (be it stack, heap or something else).