I often do this when necessary to prevent a null pointer exception:
// Example #1
if (cats != null && cats.Count > 0)
{
// Do something
}
In #1, I've always just assumed that the cats != null
needs to be first, because order of operations evaluate from left to right.
However, unlike example #1, now I want to do something if the object is null
or if the Count
is zero, therefore I'm using logical OR instead of AND:
// Example #2
if (table == null || table.Rows == null || table.Rows.Count <= 0)
{
// Do something
}
Does the order of the logical comparisons matter? Or can I also reverse the order and get the same results, such as in Example #3?
// Example #3
if (table.Rows.Count <= 0 || table.Rows == null || table == null)
{
// Do something
}
(btw, I realize I can rewrite #2 like below, but I think it's messy, and I'm still curious about the OR operators)
// Example #4
if (!(table != null && table.Rows != null && table.Rows.Count > 0))
{
// Do something
}