C# - Difference between int and int?
In C#, int and int? are two different types of data types. The key difference between them lies in their ability to handle null values.
The int
is a value type that does not include any null values, while int?
is nullable and is shorthand of nullable<int>
of value types which can have null value
int:
int
is a value type in C# that represents a 32-bit signed integer. It can hold integer values ranging from approximately -2.1 billion to 2.1 billion.
Example:
int x = 5;
int? (Nullable<int>):
int?
, also known as
Nullable<int>
, is a nullable value type in C#. It allows a value type, such as 'int', to also have a value of
null
. This is useful when you need to handle situations where a value may not be present or when dealing with databases or APIs that return null values for integer-like fields.
Example:
int? nullableInt = null;
With int?, you can assign integer values as well as null:
int? nullableInt = 10;
int? anotherNullableInt = null;
One key distinction is that regular int
(value type) cannot be assigned a null
value, whereas int?
(nullable value type) can be assigned null
. For example, by compiling the below code will result in compilation error:
int x = null; // Compilation error: Cannot convert null to int because it is a non-nullable value type.
In the below example you can see that compiler cannot convert null
to int
as it is a non-nullable value type and it's showing the compilation error:
In contrast, the following code is valid because int?
allows for null values:
int? nullableInt = null; // Valid
Now let's again illustrate this difference with a complete simple C# program:
using System;
class Program
{
static void Main()
{
int nonNullableInt = 5;
int? nullableInt = null;
Console.WriteLine("Non-nullable integer: " + nonNullableInt);
Console.WriteLine("Nullable integer: " + nullableInt);
// Trying to assign null to a non-nullable int will cause a compile-time error
// Uncommenting the following line will result in a compilation error
// nonNullableInt = null;
// Assigning a value to nullable int
nullableInt = 10;
Console.WriteLine("Nullable integer after assigning value: " + nullableInt);
}
}
Output of the program:
Non-nullable integer: 5
Nullable integer:
Nullable integer after assigning value: 10
In this example:
-
We declare
nonNullableInt
as an int
and assign it the value 5. We cannot assign null
to it; doing so would result in a compile-time error.
- We declare
nullableInt
as an int?
and initially assign it null
. Later, we assign it an integer
value, demonstrating its ability to hold both null
and integer
values.
This ability to handle null makes nullable types particularly useful in scenarios like database operations or dealing with external data sources where the presence of a value is not guaranteed.