Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is int? a value type or a reference type? [duplicate]

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.

like image 967
user2769119 Avatar asked Sep 11 '13 14:09

user2769119


People also ask

Is an int a reference type?

Int is certainly not a reference type in C#. It's a numerical struct, which is a value type. When talking about C#, it is incorrect to say int is a reference type.

Is int a reference type C#?

NET maintains an understanding of what the object is (it knows it's an int, which isn't a reference type).

Is an int array a reference type?

Array, which itself is derived from System. Object. This means that all arrays are always reference types which are allocated on the managed heap, and your app's variable contains a reference to the array and not the array itself.

Which data type is a reference type?

Examples of reference data types are class, Arrays, String, Interface, etc. Examples of primitive data types are int, float, double, Boolean, long, etc.


1 Answers

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)
like image 198
Soner Gönül Avatar answered Sep 22 '22 15:09

Soner Gönül