views:

2705

answers:

5

Hi,

In c#, is there any difference in the excecution speed for the order in which you state the condition?

if (null != variable) ...
if (variable != null) ...

Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one.

If there is no difference, what is the advantage of the first one?

+3  A: 

I guess this is a C programmer that has switched languages.

In C, you can write the following:

int i = 0;
if (i = 1)
{
    ...
}

Notice the use of a single equal sign there, which means the code will assign 1 to the variable i, then return 1 (an assignment is an expression), and use 1 in the if-statement, which will be handled as true. In other words, the above is a bug.

In C# however, this is not possible. There is indeed no difference between the two.

Lasse V. Karlsen
"In C# however, this is not possible" without the compiler complaining, as the if statement requires a boolean expression, and the one provided is of type int.
Robert Harvey
+2  A: 

In earlier times, people would forget the '!' (or the extra '=' for equality, which is more difficult to spot) and do an assignment instead of a comparison. putting the null in front eliminates the possibility for the bug, since null is not an l-value.

Most modern compilers give a warning when you do an assignment in a conditional nowadays, and C# actually gives an error. Most people just stick with the var == null scheme since it's easier to read for some people.

Rik
All C# compilers (note this is a C# question) should fail to compile an "if" statement where the expression isn't a Boolean though...
Jon Skeet
Edited to reflect this fact.
Rik
+60  A: 

It's a hold-over from C. In C, if you either use a bad compiler or don't have warnings turned up high enough, this will compile with no warning whatsoever (and is indeed legal code):

// Probably wrong
if (x = 5)

when you actually probably meant

if (x == 5)

You can work around this in C by doing:

if (5 == x)

A typo here will result in invalid code.

Now, in C# this is all piffle. Unless you're comparing two Boolean values (which is rare, IME) you can write the more readable code, as an "if" statement requires a Boolean expression to start with, and the type of "x=5" is Int32, not Boolean.

I suggest that if you see this in your colleagues' code, you educate them in the ways of modern languages, and suggest they write the more natural form in future.

Jon Skeet
My colleagues all drive me nuts with this, and wanting curly-brackets even for a single statement after the if... (in case you add something later 'without realising'). Roll on F# and Boo (and YAML), if your language is unreadable without indentation, make it part of the language, I say.
Benjol
Adding braces *is* reasonable, IMO - C# certainly doesn't make any attempt to stop it from being a problem. That's very different to the "constant == variable" issue.
Jon Skeet
a if( this!=that ){ performAsSuch(); } is quite healthy actually. The argument of "later addition" seams to me about as fragile as not avoiding/spoting if (a=5) typos
jpinto3912
@jpinto: I'm not really sure what you're trying to say here - that you *do* like braces around single statements, or that you don't? The difference between this and the variable business in the question is that in C# the code with a typo is *invalid* code so the compiler will stop it. The same *isn't* true for not putting braces in.
Jon Skeet
A: 

To me it's always been which style you prefer

@Shy - Then again if you confuse the operators then you should want to get a compilation error or you will be running code with a bug - a bug that come back and bite you later down the road since it produced unexpected behaviour

TheCodeJunkie
I don't think I've ever heard of anyone preferring the "constant == variable" form *other* than for reasons of safety, which are already dealt with in C#.
Jon Skeet
I prefer "variable == constant" myself, but I've seen programmers adopt the reversed because they feel it reads more natural to them.
TheCodeJunkie
Were they all people with years of C brainwashing behind them, or was it a genuine choice?
Jon Skeet
A: 

One more thing... If you are comparing a variable to a constant (integer or string for ex.), putting the constant on the left is good practice because you'll never run into NullPointerExceptions :

int i;
if(i==1){        // Exception raised: i is not initialized. (C/C++)
  doThis();
}

whereas

int i;
if(1==i){        // OK, but the condition is not met.
  doThis();
}

Now, since by default C# instanciates all variables, you shouldn't have that problem in that language.

m_oLogin
I am not sure what compiler you are using for the first bit of code, but it should compile (generally with a warning). The value of i is undefined, but it does have SOME value.
Dolphin
Of course both codes will compile! That's exactly the problem. Try running the first code and you'll understand what I meant by "Exception raised"...
m_oLogin
@m_oLogin, is also don't get the difference between the two. Can you ellaborate?
mfazekas
No exception unless you declare int *i in C/C++, and even in that case it will compare pointers and not throw any exception ... Like Dolphin stated the value is undefined but it will not generate any Exceptions.
Cobusve