Conditional styles: if (0 == resultIndex) vs if (resultIndex == 0)

Most of us write conventions, such as:

if (resultIndex == 0) 

... but sometimes I come across someone who writes them, like:

 if (0 == resultIndex) 

... and it’s interesting that these people were authors and seemingly rather hot codons.

So why do some people choose the back style? Is there any story behind this? Readabililty?


Duplicate: Why in C #? often appears "null! = variable" instead of "variable! = null".

+1
source share
5 answers

This has been asked many times, but I cannot find a dup.

In essence, this style is a hangover from C, where a common mistake for

 if (c == 5) //Comparison 

was

 if (c = 5) //Assignment 

In the latter case, the compiler should not complain, so people wrote it that way to reduce the likelihood of this event.

 if (5 == c) 
+6
source

This is a legacy from C, where a common mistake would be to write

 if (x = 0) {...} 

If you taught yourself to write these tests differently, then the compiler will complain when you create == typo, instead of silently adding an error.

+7
source

Because (in C, where most of these programmers probably learned, I can’t remember whether it supports C #), if you leave the = character in the β€œnormal” style, you will overwrite the value you are trying to compare (and you will check the logical value of the job). If you do this in the back style, you will get a compiler error.

+2
source

In C #, integer values ​​are not implicitly discarded in boolean, so if (a = 0) gives a compiler error and does not compile. Therefore, this practice is deprecated and not fully specified in C #.

+1
source

The main reason for this, I believe, is to prevent errors such as:

 if (variable = 0) 

Where you assign in a state instead of a comparison. The reason is that this will not work otherwise, because you have a constant on the left side of the expression.

So, if you mistakenly write:

 if (0 = variable) 

You got a compilation error while trying to assign something to a constant.

In my opinion, this is more important in terms of programming style, but it can still be good advice for new programmers. But as soon as you are a little more experienced, errors like this do not occur, and if they do, you should easily track them.

0
source

All Articles