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

2019-02-26 16:51发布

问题:

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...



标签: c# .net null