-2

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
}
Bill
  • 915
  • 2
  • 13
  • 23
  • 1
    If you want to check if it's `null`, check if it's `null`. `if (myInt == null)` or `if (!myInt.HasValue)`. If 0 is already an invalid value, why bother making it a nullable variable in the first place? – itsme86 Nov 14 '19 at 19:23
  • 2
    This check is correct if you really want to know if `myInt` is positive -- `null` is not considered positive (in fact, any comparison between a nullable type that's `null` and a non-`null` value is considered `false`; the language provides overloaded versions of the operators that apply to nullables "for free"). It is not correct if you want to test if there is any value at all. – Jeroen Mostert Nov 14 '19 at 19:25

3 Answers3

3

It will compile, but something like the following is probably safer:

public int? myInt;

if (myInt.HasValue && myInt > 0)
{
    Do something
}
Ross Gurbutt
  • 969
  • 1
  • 8
  • 15
2

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
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • Note that it works for this particular case, but it is not a general transformation, because `default(int)` is `0`. If `myInt` is `null`, then `myInt == 0` is `false`, but `myInt.GetValueOrDefault() == 0` is `true`. If you really wanted this then arguably `(myInt ?? 0)` would be clearer still. – Jeroen Mostert Nov 14 '19 at 19:32
  • I think I said that already, but yes, if you want to know if the value is set to the default for the type, then `GetValueOrDefault` isn't useful. – Rufus L Nov 14 '19 at 19:35
1

int? is a syntax sugar for Nullable<int> so you can call myInt.HasValue to check for null value.

Nullable class reference

Feo
  • 161
  • 6