Check an integer value is Null in c#
Nullable<T>
(or ?
) exposes a HasValue
flag to denote if a value is set or the item is null.
Also, nullable types support ==
:
if (Age == null)
The ??
is the null coalescing operator and doesn't result in a boolean expression, but a value returned:
int i = Age ?? 0;
So for your example:
if (age == null || age == 0)
Or:
if (age.GetValueOrDefault(0) == 0)
Or:
if ((age ?? 0) == 0)
Or ternary:
int i = age.HasValue ? age.Value : 0;
Several things:
Age
is not an integer - it is a nullable integer type. They are not the same. See the documentation for Nullable<T>
on MSDN for details.
??
is the null coalesce operator, not the ternary operator (actually called the conditional operator).
To check if a nullable type has a value use HasValue
, or check directly against null
:
if(Age.HasValue)
{
// Yay, it does!
}
if(Age == null)
{
// It is null :(
}
There is already a correct answer from Adam, but you have another option to refactor your code:
if (Age.GetValueOrDefault() == 0)
{
// it's null or 0
}