Something special in true ==?

Currently, I need to make a replacement for the college and change its code.

I found a lot of conditions like

if (true == variablename) {...} 

I'm just wondering if there is anything special about this syntax? Like most of us, I'll just write

 if (variablename) {...} 

instead of this. The truth on the left side of the state annoys me. It would be right, I would just expect the college to not advance in Boolean conditions.

Is there a difference in performance or something like that, putting true at the beginning?

+4
source share
3 answers

This probably remains from learning C / C ++, where it was typical to bite this error:

 if (variablename = true) { ... } 

Before the compilers were set up to warn about this (note that it does the job, not the comparison), the above code silently executed an error.

However, if you had learned to write the expression differently, you would not have bitten the above code, because it would not compile in this form:

 if (true = variablename) { ... } 

In C #, however, this is not a problem, you can write it as you showed without comparison (if it is still compared with true ), or put a literal on the right side of the comparison operator.

+11
source

It makes no difference, it's just a code style. I.e.

The only thing that comes to my mind:

if variablename becomes a Nullable type (due to some refactoring, input error, or whatever), this code will still compile and work as expected,

Instead, write as:

 if (variablename) {...} 

you get a compile-time error, so you have to change the code.

+4
source

Is there a difference in performance or something like that, putting true at the beginning?

I think that having truth in the beginning is common to many people who have a C ++ background; where it would be easy to highlight a value by setting if(b = true) instead of if(b==true) ; whereas you could not do the same with if(true = b)

+2
source

Source: https://habr.com/ru/post/1488533/


All Articles