Is this conditional check OK? It works fine but I'm wondering if there is a potential hidden issue. It sure is a lot simpler than having to check for null.
public int? myInt;
if (myInt > 0)
{
Do something
}
Is this conditional check OK? It works fine but I'm wondering if there is a potential hidden issue. It sure is a lot simpler than having to check for null.
public int? myInt;
if (myInt > 0)
{
Do something
}
It will compile, but something like the following is probably safer:
public int? myInt;
if (myInt.HasValue && myInt > 0)
{
Do something
}
You can use the GetValueOrDefault
method of Nullable<T>
, which returns the default value of the type if it's null
, otherwise it returns the actual value (this works for you since you're comparing against 0
, which is default(int)
):
if (myInt.GetValueOrDefault() > 0)
{
// Do something here
}
int?
is a syntax sugar for Nullable<int>
so you can call myInt.HasValue
to check for null value.