What is the benefit if we write
if( 1 == myobject) { //some code }

as opposed to

if( myobject == 1 ){ //some code } ?

 Posted by Niladri.Biswas on 7/13/2012 | Category: C# Interview questions | Views: 2948 | Points: 40

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 

Comments or Responses

Posted by: Akiii on: 7/21/2012 | Points: 10
Good point...

Thanks and Regards

Login to post response