Is there any difference between below two statements
if (null != obj)
and
if (obj != null)
If both treate
They are exactly the same.
Some people prefer to put the null as the first part of the expression to avoid errors like this
if (obj = null) // should be obj == null
But of course this doesn't apply to the !=
operator, so in your example it's just a difference of style.
The use of the first form
if (blah == obj)
stems from the days when compilers would not catch if (obj = blah)
i.e. unintentional assignment, unless compile warning level was set to maximum
The first is a Yoda condition. Use it you should not.
No, there is not. It's exactly the same.
The style null == obj
is sometimes just used to prevent the common typo obj = null
to not accidently assign null to a variable, but with !=
there's absolutely no reason to do so.
In .NET it won't actually compile for the typo obj = null
.
So the compiler prevents you from accidently doing it.
The Yoda condition comes originally from other languages, where this compiler feature is missing.
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.
No, but the second way is more common and more readable (and more logical in my opinion)