How to set null value to int in c#?
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)
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.