Zero check, which is better? "null ==" or "== null"

Dupe: Null Difference

Throughout my life, I came across an article that explained that the following were not equal (in C #):

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

The article explains that the latter was preferable because it led to a more accurate test. Since then I have been coding this way. Now that I understand much more, I was looking for an article or something similar to find out what the exact data was, but I can not find anything on this.

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

+2
source share
5 answers

This is an old habit of stopping you from typing if (o = null) . if (null = o) is a syntax error. kind are meaningless in C # because null values โ€‹โ€‹are never forced to boolean.

+9
source

The latter is a delay from the days of C / C ++, where you could accidentally assign a value instead of a comparison. C # will not allow you to do this, so either / or is acceptable (but I believe the first is more readable).

+3
source

There is no difference in C #. This is an old habit of C / C ++ developers to avoid a common mistake, where is the correct syntax:

 if(o = null) 

In C #, which will not compile, but in C and C ++ it would leave you with a rather nasty bug. Therefore, many people are used to doing

 if(null == o) 
+2
source

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

0
source

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

 "name".equals(name) null == obj "55".compareTo(numString) 

etc. Just avoid unnecessary NullPointerExceptions ...

0
source

All Articles