views:

145

answers:

6

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  A: 

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

UpTheCreek
A: 

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

SLC
+13  A: 
(Not A)  AND  (Not B)

is NOT equal to

Not (A And B)
Mitch Wheat
Indeed, looks like De Morgan's laws got sidetracked.
Svend
+5  A: 

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))
Lasse V. Karlsen
Yes, Got it . Thanks a lot.
Ram
A: 

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) {
  // ...
}
Danvil
A: 

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

Fish