I'm working on a project where i find i'm checking for the following in many, many places:
if(item.Rate == 0 || item.Rate == null) { }
more as a curiousity than anything, what's the best way to check for both cases?
I've added a helper method which is:
public static bool nz(object obj) { var parsedInt = 0; var parsed = int.TryParse(obj.ToString(), out parsedInt); return IsNull(obj) || (parsed && parsedInt == 0); }
Is there a better way?
The compiler replaces null comparisons with a call to HasValue , so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.
Some int value as an int? is definitely non-null and null is definitely null. The compiler realizes that and since a non-null value is not equal to a definite null value, the warning is given. The compiler also optimizes this away because it is always false. It won't even load the x variable at all.
operators with nullable type. You can also use GetValueOrDefault(T) method to get the assigned value or the provided default value, if the value of nullable type is null. You can also use null-coalescing operator(??) to assign a value to the underlying type originate from the value of the nullable type.
I like if ((item.Rate ?? 0) == 0) { }
Update 1:
You could also define an extension method like:
public static bool IsNullOrValue(this double? value, double valueToCheck) { return (value??valueToCheck) == valueToCheck; }
And use it like this:
if(item.IsNullOrValue(0)){}
// but you don't get much from it
Although I quite like the accepted answer, I think that, for completeness, this option should be mentioned as well:
if (item.Rate.GetValueOrDefault() == 0) { }
This solution
((item.Rate ?? 0) == 0)
(this might be a matter of taste, though).¹ This should not influence your decision, though, since these kinds of micro-optimization are unlikely to make any difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With