Nate
Nate

Reputation: 919

Double negative IF statements

While reviewing code, I have come across a few if staments using ! followed by an != in the assessment e.g.

if (!(fs.ReadByte() != (byte)'D' ||
      fs.ReadByte() != (byte)'I' ||
      fs.ReadByte() != (byte)'C' ||
      fs.ReadByte() != (byte)'M'))
{
    Console.WriteLine("Not a DCM");
    return;
}

Is there any reason to use a double negative over assessing positive e.g.

if ((fs.ReadByte() == (byte)'D' ||
     fs.ReadByte() == (byte)'I' ||
     fs.ReadByte() == (byte)'C' ||
     fs.ReadByte() == (byte)'M'))
{
    Console.WriteLine("Not a DCM");
    return;
}

Thanks

Upvotes: 1

Views: 1811

Answers (1)

David Robinson
David Robinson

Reputation: 78600

Those two are different. The first says "None of these are not equal", the second says "any of these are equal".

If you applied the ! operator across them, you'd have to change the || to an &&:

if ((fs.ReadByte() == (byte)'D' &&
     fs.ReadByte() == (byte)'I' &&
     fs.ReadByte() == (byte)'C' &&
     fs.ReadByte() == (byte)'M'))
{
    Console.WriteLine("Not a DCM");
    return;
}

Upvotes: 5

Related Questions