Checking for null, which is better? “null ==” or “==null” [duplicate]

心已入冬 提交于 2019-12-31 02:54:13

问题


Dupe: Null Difference

A lifetime ago I came across an article that explained that the following were not equal (in c#):

if (o == null) {}
if (null == o) {}

The article explained that the latter was preferred because it resulted in a more accurate test. I've been coding like that ever since. Now that I understand so much more I was looking for the article, or another like it, to see what the exact findings were, but I can't find anything on the subject.

Thoughts? Is there a difference? First glance would say no. But who knows what happens in the bowels of IL and C# compilation.


回答1:


it's an old habit to prevent you from typing if (o = null). if (null = o) is a syntax error. kind of pointless in C#, because null values aren't ever coerced into booleans.




回答2:


The latter is a holdover from the C/C++ days, where it was possible to accidentally assign a value instead of compare. C# won't allow you to do this, so either/or is acceptable (but I find the former more readable).




回答3:


In c# there's no difference. It's an old habit from C/C++ developers to avoid a common bug where this is correct syntax:

if(o = null)

In C# that wouldn't compile but in C and C++ it would, leaving you with a pretty nasty bug. Therefore, many people got used to doing

if(null == o)



回答4:


Irrelevant for C#, this is from C. See this question for a discussion.




回答5:


I work with Java ..and I do have the habit of having constants on the LHS for all commutative comparisons.

"name".equals(name)

 null == obj

"55".compareTo(numString)

etc..Just avoiding unnecessary NullPointerExceptions...



来源:https://stackoverflow.com/questions/424842/checking-for-null-which-is-better-null-or-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!