Why int can't be null? How does nullable int (int?) work in C#?
Solution 1
int
is a primitive type and only ReferenceType
s (objects) are nullable. You can make an int
nullable by wrapping it in an object:
System.Nullable<int> i;
-or-
int? i;
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/using-nullable-types
Solution 2
Value types like int
contain direct values rather than references like ReferenceType
. A value cannot be null but a reference can be null which means it is pointing to nothing. A value cannot have nothing in it. A value always contain some kind of value
Nullable or Nullable types are special value types which in addition to normal values of value types also support additional null value just like reference types
Solution 3
You can have a nullable int by using int? or Nullable<int>
both are exactly the same thing.
Solution 4
An int is a value type. It is really of type Int32. Objects that can be nullable are reference types. At a basic level the difference is that a value type will store the value with the variable where a reference type will store a reference to the value. A reference can be null, meaning that it doesn't point to a value. Where a value type always has a value.
Nullable wraps a value type to allow you to have the option of being null. Using int? is just a compiler shortcut to declare a nullable type.
Solution 5
Objects are reference types and they can reference nothing or NULL, however int is a value type, which can only hold a value, and cannot reference anything.
Rusi Nova
Updated on June 04, 2022Comments
-
Rusi Nova about 2 years
I am new to C# and just learned that objects can be null in C# but
int
can't.Also how does nullable int (
int?
) work in C#? -
Thomson almost 13 yearsSomeone gives the down vote should show the reason. Nullable<T> add an extra private bool filed
hasValue
to the structure definition to express null of int, besides, the CLR need to be revised a little to deal with this special structure when comparing it with null. The primitive int could not represent null since all its binary permutations represent value of int, in the condition that it has 4 bytes in the stack. -
B Bulfin almost 13 yearsI didn't downvote it, but may have been due to citing an obscure fact about the memory layout without any supporting documentation. Otherwise, I'm not sure.
-
Aaron Franke over 5 yearsIs
int?
slower thanint
is? Does it use more memory? -
Ilia Choly over 5 years@AaronFranke yeah, gets wrapped in an extra object.