Conditional Statements difference

后端 未结 7 1469
日久生厌
日久生厌 2020-12-20 16:24

Is there any difference between below two statements

if (null != obj)

and

if (obj != null)

If both treate

相关标签:
7条回答
  • 2020-12-20 16:32

    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.

    0 讨论(0)
  • 2020-12-20 16:32

    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

    0 讨论(0)
  • 2020-12-20 16:39

    The first is a Yoda condition. Use it you should not.

    0 讨论(0)
  • 2020-12-20 16:40

    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.

    0 讨论(0)
  • 2020-12-20 16:40

    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.

    0 讨论(0)
  • 2020-12-20 16:48

    No, but the second way is more common and more readable (and more logical in my opinion)

    0 讨论(0)
提交回复
热议问题