When to use !() or != when if not null
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.
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.