开发者

&& Operation in .NET

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

 if (!StartTime.Equals(DateTime.MinValue) &&
    !CreationTime.Equa开发者_StackOverflow中文版ls(DateTime.MinValue))

Or

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

What is the difference between the two?


(Not A)  AND  (Not B)

is NOT equal to

Not (A And B)


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜