I currently have to do some holiday replacement for a collegue and have to change a bit of his code.
I found a lot of conditions like
if (true == variablename) {...}
I just wonder if there is something special about this syntax? Like most of us I would just write
if (variablename) {...}
instead. What irritates me is the true at the left side of the condition. Would it be on the right side I would just expect the collegue is not advanced in boolean conditions.
Is there any performance difference or something like that by putting true at the beginning?
This is likely a leftover from learning C/C++, where it was typical to be bitten by this bug:
if (variablename = true) { ... }
Before compilers was adjusted to warn about this (notice that it does an assignment, not a comparison), the above code was silently executing with a bug.
However, if you learned to write the expression the other way around, you would not get bitten by the above code because it would not compile in this form:
if (true = variablename) { ... }
In C#, however, it is not a problem, you can write it like you showed without the comparison (as long as it is comparing to true
anyway), or put the literal on the right side of the comparison operator.
No there is no any difference, it's just a code style. That is.
The only thing that come to my mind is:
if variablename
becomes Nullable type (due some refactoring, typing error or whatever else), this code will still compile and work as expected.
Instead if you write like:
if (variablename) {...}
you will get compile time error, so you will be forced to change the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With