Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use !() or != when if not null

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#?

like image 603
Nicholas Murray Avatar asked Jan 05 '12 09:01

Nicholas Murray


People also ask

What is #if 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.

How or condition works in C#?

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.


3 Answers

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.

like image 158
Oded Avatar answered Oct 06 '22 09:10

Oded


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.

like image 10
Jon Skeet Avatar answered Oct 06 '22 08:10

Jon Skeet


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.

like image 6
balexandre Avatar answered Oct 06 '22 09:10

balexandre