Answer: The
if (1 == myobject) { //some code } is a safe way of writing an if statement. It comes from C/C++ where the condition is an expression evaluated to an int.
If the result is zero that means false, anything else is true.
We can write something like
if (myobject == 1){ //some code }
but if we weren’t careful we could also write
if (myobject = 1) { //some code }
in which case we have an assignment that always evaluates to 1 and thus is always true.This will compile and run with no problems, but the result wouldn’t be as expected. So C/C++ programmers started to write things like
if (1 == myobject) { //some code }
This won’t compile if we misspell it, so we always had to write it as we meant to write it. Later on this became a good practice and we use it in all the languages - C# for example.
Asked In: Many Interviews |
Alert Moderator