Alex Rivera | Logout

Conditional Statements difference

Asked 2011-02-10T13:40:09.007
9

Is there any difference between below two statements

if (null != obj)

and

if (obj != null)

If both treated same which will be preferable?

Edit
Report

1 Answer

1

First type of statement came from C/C++, where was possible to pass not boolean values to condition verification. E.g. anything not 0 was true, and zero was false:

if (5) { } // true
if (0) { } // false

Sometimes it created problems if you forgot to type one '=' char:

if (x = 5) { }   // this was true always and changed x value
if (x == 5) { }  // this was true, if x was equal to 5

So, Yoda syntax was used, to receive compiler error in case one '=' was missed:

if (5 = x) { }   // this was generating compiler error for absent-minded programmers
if (5 == x) { }  // this was true, if x was equal to 5

C# allow only boolean value in conditions, So

if (x = 5) { }   // this won't compile
if (x == 5) { }  // this is true, if x was equal to 5

What about boolean types?

if (y = true) { }
if (y == true) { }

Well, this is useless code, because you can just write if (y). Conclusion: Yoda syntax is gone with C/C++ and you do not need to use it anymore.

answered 2011-02-10T13:53:49.773

Your Answer