Conditional Statements difference

后端 未结 7 1500
日久生厌
日久生厌 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:54

    The difference here is the code generated. The two will not generate the exact same code, but in practice this will have no bearing on the results or performance of the two statements.

    However, if you create your own types, and override the inequality operator, and do a poor job, then it will matter.

    Consider this:

    public class TestClass
    {
        ...
    
        public static bool operator !=(TestClass left, TestClass right)
        {
            return !left.Equals(right);
        }
    }
    

    In this case, if the first argument to the operator is null, ie. if (null != obj), then it will crash with a NullReferenceException.

    So to summarize:

    • The code generated is different
    • The performance and end results should be the same
      • Except when you have broken code in the type involved

    Now, the reason I think you're asking is that you've seen code from C, which typically had code like this:

    if (null == obj)
    

    Note that I switched to equality check here. The reason is that a frequent bug in programs written with old C compilers (these days they tend to catch this problem) would be to switch it around and forget one of the equal characters, ie. this:

    if (obj = null)
    

    This assigns null to the variable instead of comparing it. The best way to combat this bug, back then, would be to switch it around, since you can't assign anything to null, it's not a variable. ie. this would fail to compile:

    if (null = obj)
    

提交回复
热议问题