Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why int can't be null? How does nullable int (int?) work in C#?

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#?

like image 780
Rusi Nova Avatar asked Aug 06 '11 15:08

Rusi Nova


People also ask

Can int be nullable?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.

What is the difference between nullable int and int?

No difference. int? is just shorthand for Nullable<int> , which itself is shorthand for Nullable<Int32> . Compiled code will be exactly the same whichever one you choose to use.

How do I assign a null to a nullable integer?

You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.

Is nullable int a value type?

Nullable types are neither value types nor reference types.


1 Answers

int is a primitive type and only ReferenceTypes (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

like image 55
Ilia Choly Avatar answered Sep 24 '22 09:09

Ilia Choly