1

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

Nate
  • 919
  • 2
  • 9
  • 18

1 Answers1

5

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;
}
David Robinson
  • 77,383
  • 16
  • 167
  • 187
  • Well spotted. Then would there be any other reason if the || was replaced by &&? – Nate Aug 25 '12 at 23:12
  • @Nate: What is the code trying to do? We think it might be backwards. – David Robinson Aug 25 '12 at 23:16
  • @David Robinson It's an answered question related to something I'm working on http://stackoverflow.com/a/2384533/925922. – Nate Aug 25 '12 at 23:19
  • @Nate: It's a mistake. This code you provide will give the "Not a DCM" output only if the file *does* start with DICM. – David Robinson Aug 25 '12 at 23:24
  • @David Robinson I thought it might have been an error. But I'm sure I've seen a similar 'if' technique used somewhere else so I thought I'd ask if there was a reason for it. Thanks. – Nate Aug 25 '12 at 23:27
  • 1
    This is called De Morgan's Law - you can move the `!` inside the parts of the expression if you switch `||` with `&&`. (Obviously in this case it then cancels out with the `!=` resulting in `==`.) – Neil Aug 25 '12 at 23:36
  • +1 for being amusingly bug-compatible with the first version :) – Jon Hanna Aug 26 '12 at 00:05