C# do you need to check if something has a value and if something is greater than 0?
The code is probably redundant.
If i is int?
then:
if (i.HasValue && i.Value > 0)
is equivalent to:
if (i > 0)
From MSDN:
When you perform comparisons with nullable types, if the value of one of the nullable types is null and the other is not, all comparisons evaluate to false except for != (not equal). It is important not to assume that because a particular comparison returns false, the opposite case returns true. In the following example, 10 is not greater than, less than, nor equal to null. Only num1 != num2 evaluates to true.
It might be that the value for the variable has different meanings in that context.
int? someNumber = null; //might mean "there is no value"
int? someOtherNumber = 0; //might mean "the user has selected: 0"
The following:
class Program {
static void Main(string[] args) {
int? i = null;
if (i > 0) { Console.WriteLine(">0");
} else { Console.WriteLine("not >0");
}
if (i < 0) { Console.WriteLine("<0");
} else { Console.WriteLine("not <0");
}
if (i == 0) {Console.WriteLine("==0");
} else { Console.WriteLine("not ==0");
}
Console.ReadKey();
}
}
will output
not >0
not <0
not ==0
without throwing an exception. So the null/HasValue check in this case is redundant. There is one small difference. The following:
(i.HasValue && (i.Value == 0))
is about twice as fast as
(i == 0)
when i is null although both are so fast it's not an important difference. When i has a value, the two comparisons take about the same amount of time.