Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

null

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.

like image 548
Tony Basallo Avatar asked Feb 02 '26 23:02

Tony Basallo


1 Answers

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.

like image 191
Jimmy Avatar answered Feb 05 '26 13:02

Jimmy