0

For the following code:

private decimal? Quantity;
if (Quantity.HasValue && Quantity.Value !=0)
{
    // 1
}
if (Quantity !=0)
{
    // 2
}

Can I always use #2 instead?

Ciaran Martin
  • 578
  • 4
  • 12
  • 1
    yes (need more characters) – M.kazem Akhgary Sep 30 '15 at 10:12
  • 2
    Can you not just test it and see? – Chris Sep 30 '15 at 10:13
  • Yes, `0` is lifted to be a `decimal?` and the comparison will work. – CodeCaster Sep 30 '15 at 10:13
  • It's *impossible* to `Quantity` while having *no value* be equal to zero ;) So you can use `Quantity != 0` – Dmitry Bychenko Sep 30 '15 at 10:14
  • Also to correct those saying yes they are wrong. If Quantity is null the first if will be false (since HasValue will be false) but the second will be true (since null != 0). I found this out by the power of writing code and seeing what happens. :) – Chris Sep 30 '15 at 10:17
  • Thanks everyone, esp Chris. I had issues with LinqPad but I just discovered the same as you i.e. that if Quantity = null, then the second if will fire. This makes sense as null is not equal to zero, but what I'm actually trying to achieve is does Quantity have a real non-zero value which is demonstrated in # 1. Therefore I need to actually use #1 for my purposes. decimal? Quantity = null; if (Quantity != 0) { Console.WriteLine(1); } – Ciaran Martin Sep 30 '15 at 10:19

0 Answers0