Ram
Ram

Reputation: 11644

&& 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.Equals(DateTime.MinValue))

Or

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

What is the difference between the two?

Upvotes: 4

Views: 238

Answers (6)

Fish
Fish

Reputation: 1

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

Upvotes: 0

Danvil
Danvil

Reputation: 22981

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

Upvotes: 1

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391296

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

Upvotes: 5

Mitch Wheat
Mitch Wheat

Reputation: 300519

(Not A)  AND  (Not B)

is NOT equal to

Not (A And B)

Upvotes: 13

NibblyPig
NibblyPig

Reputation: 52932

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

Upvotes: 0

UpTheCreek
UpTheCreek

Reputation: 32381

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

Upvotes: 1

Related Questions