Why does one often see “null != variable” instead

2018-12-31 16:29发布

In c#, is there any difference in the excecution speed for the order in which you state the condition?

if (null != variable) ...
if (variable != null) ...

Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one.

If there is no difference, what is the advantage of the first one?

8条回答
栀子花@的思念
2楼-- · 2018-12-31 17:25

To me it's always been which style you prefer

@Shy - Then again if you confuse the operators then you should want to get a compilation error or you will be running code with a bug - a bug that come back and bite you later down the road since it produced unexpected behaviour

查看更多
只靠听说
3楼-- · 2018-12-31 17:25

One more thing... If you are comparing a variable to a constant (integer or string for ex.), putting the constant on the left is good practice because you'll never run into NullPointerExceptions :

int i;
if(i==1){        // Exception raised: i is not initialized. (C/C++)
  doThis();
}

whereas

int i;
if(1==i){        // OK, but the condition is not met.
  doThis();
}

Now, since by default C# instanciates all variables, you shouldn't have that problem in that language.

查看更多
登录 后发表回答