Whilst refactoring code I changed the all the if not null conditions to follow the majority convention in my code of
if (!(foo == null))
instead of
if (foo != null)
Is there any advantage in either statement?
Is there any advantage in either statement in c#?
#if : Opens a conditional compilation, where code is compiled only if the specified symbol is defined. #elif : Closes the preceding conditional compilation and opens a new conditional compilation based on if the specified symbol is defined.
The conditional logical OR operator || , also known as the "short-circuiting" logical OR operator, computes the logical OR of its operands. The result of x || y is true if either x or y evaluates to true . Otherwise, the result is false . If x evaluates to true , y is not evaluated.
I find the second one more readable.
Apart from that, there is no difference.
It is more important to pick a convention with your team and stick to it within any one particular codebase.
Assuming you don't have broken ==
/ !=
operator overloads, I'd just use the second form for the benefit of simplicity / readability. If you do have broken overloads such that there's a semantic difference between the two, then I'd suggest fixing those overloads :)
In the rare case where foo == null
is a clearer indication of something, I'd probably refactor it to use a local variable:
bool somethingIsMissing = foo == null;
if (!somethingIsMissing)
{
...
}
Parentheses round the foo == null
are now optional - use or don't, according to taste. The main thing is that you can use the variable name to make the semantic meaning really clear.
normally if (!(foo == null))
is used when you have more variables to considerate, for example
if (!(f1 == 'a' && f2 != 'b'))
sometimes is just easier this way that transform everything to the opposite, specially when you using bitwise operators.
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