Reverse Conditionals

One thing about C# style that I get asked quite a lot is why I tend to write if statements like this…

if (null != args)

It’s not how most people think. It seems far more logical written this way round…

if (args != null)

It’s actually a hang-on from my days as a plain old C developer, most of the time it’s not relevant to C# but there’s one particular instance where it is.

bool someBoolean = false;
bool someOtherBoolean = true;
if(someBoolean = someOtherBoolean)
     Console.WriteLine("The if condition evaluated to true!");
Console.WriteLine(String.Format("someBoolean is [{0}], someOtherBoolean is [{1}]", someBoolean, someOtherBoolean));

So when we run this, we might not get the result we expect.
This is because in C# assignment operations have a result. Instead of comparing the two items in the if statement (==) we assigned the value in someOtherBoolean to someBoolean (=). Basically we just used = where we should have used ==, it’s an easy mistake to make and in this instance it compiles and runs, it just doesn’t do what we want, at all…
I actually wrote about this in an article some time ago, but back then I was talking about doing it deliberately, and as part of a work of extreme evil.

OK, so that’s a convoluted example and in reality you’re unlikely to cause yourself serious problems in C# because C# is very strict about the result of whatever’s in an if statement being Boolean. So if you did accidentally write this, it wouldn’t compile.

if(someObject = null)
    someObject = new someType();

This is because the result of assigning null to someObject is null, which is not a Boolean.

However in C the equivalent will compile and will run. In C anything that evaluates to zero is treated as false and anything that evaluates to non-zero is treated as true.

#include <stdio.h>
#include <stdlib.h>

typedef struct
    int SomeProperty;
} SomeType;

int main(int argc, char* argv)
    SomeType *someStruct = NULL;
    if(someStruct = NULL)
        someStruct =  (SomeType*)malloc(sizeof(SomeType));
    someStruct->SomeProperty = 42;

This will crash every time, because we’re actually assigning NULL to the value someStruct. The result of that assignment is zero, which evaluates to false, so execution skips the contents of the if statement and goes directly to where the structure is accessed – the structure that we’ve just assigned to NULL.

Bit if we reverse the way we do the comparison…

if(NULL = someStruct)
    someStruct = (SomeType*)malloc(sizeof(SomeType));
someStruct->SomePropery = 42;

This won’t compile, because you can’t assign the value in the variable someStruct to the constant NULL.

So, in a nutshell, that’s why when I’m comparing a variable to a constant I tend to put the constant first.

One thought on “Reverse Conditionals

Comments are closed.