문제

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?

도움이 되었습니까?

해결책

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

다른 팁

(Not A)  AND  (Not B)

is NOT equal to

Not (A And B)

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

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

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

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top