How to set null value to int in c#?
int value=0;
if (value == 0)
{
value = null;
}
How can I set value
to null
above?
Any help will be appreciated.
Solution 1:
In .Net, you cannot assign a null
value to an int
or any other struct. Instead, use a Nullable<int>
, or int?
for short:
int? value = 0;
if (value == 0)
{
value = null;
}
Further Reading
- Nullable Types (C# Programming Guide)
Solution 2:
Additionally, you cannot use "null" as a value in a conditional assignment. e.g...
bool testvalue = false;
int? myint = (testvalue == true) ? 1234 : null;
FAILS with: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'.
So, you have to cast the null as well... This works:
int? myint = (testvalue == true) ? 1234 : (int?)null;
UPDATE (Oct 2021):
As of C# 9.0 you can use "Target-Typed" conditional expresssions, and the example will now work as c# 9 can pre-determine the result type by evaluating the expression at compile-time.
Solution 3:
You cannot set an int
to null
. Use a nullable int (int?
) instead:
int? value = null;
Solution 4:
int does not allow null, use-
int? value = 0
or use
Nullable<int> value