4

Which one out of the following two should be preferred while doing && operation on two values.

 if (!StartTime.Equals(DateTime.MinValue) && !CreationTime.Equals(DateTime.MinValue)) 

Or

 if (!(StartTime.Equals(DateTime.MinValue) && CreationTime.Equals(DateTime.MinValue)) 

What is the difference between the two?

1

6 Answers 6

13
(Not A) AND (Not B) 

is NOT equal to

Not (A And B) 
Sign up to request clarification or add additional context in comments.

1 Comment

Indeed, looks like De Morgan's laws got sidetracked.
5

Personally I use the former, I find it easier to read if as much information as possible is as close to the point I need it as possible.

For instance, just now I was wondering if your question was whether it was better to put the expression on two lines or just one, until I noticed the part about the not and the parenthesis.

That is, provided they mean the same, which your expressions doesn't.

ie.

if (!a && !b) 

is not the same as:

if (!(a && b)) 

Rather:

if (!(a || b)) 

Comments

1

Well, it depends what you want. They both do different things, and either might be correct in the given context.

Comments

1

Regarding only the formatting, I prefere:

if(MyFirstExtremlyLongExpressionWhichBarelyFitsIntoALine && MySecondExtremlyLongExpressionWhichBarelyFitsIntoALine && MyThirdExtremlyLongExpressionWhichBarelyFitsIntoALine ) { // ... } 

But if the expressions are really long and compley, you should define temporary variables to enhance readability:

bool condition1 = MyFirstExtremlyLongExpressionWhichBarelyFitsIntoALine; bool condition2 = MySecondExtremlyLongExpressionWhichBarelyFitsIntoALine; bool condition3 = MyThirdExtremlyLongExpressionWhichBarelyFitsIntoALine; if(condition1 && condition2 && condition3) { // ... } 

The latter also clarifies your intention, if you are doing more complex boolean expressions:

if((!condition1 && !condition2) && condition3) { // ... } 

Comments

0

The first one is much more readable, and readability is the most important thing here.

Is the second one actually equivelent to the first statement? Shouldn't it be ||?

Comments

0

If you give put in the values you will see

(!1 && !1) == (0 && 0) == 0 (!1 && !0) == (0 && 1) == 0

!(1 && 1) == !1 == 0 !(1 && 0) == !0 == 1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.