Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why null == myVar instead of myVar == null? [duplicate]

Tags:

c#

.net

vb.net

Possible Duplicate:
Why does one often see “null != variable” instead of “variable != null” in C#?

I see it from times to times and I'd like to know why. Is there any difference at all?

like image 408
devoured elysium Avatar asked Sep 20 '09 23:09

devoured elysium


2 Answers

It's an old habit to avoid the accidental typo of myVar = null (whoops). It's still helpful in some languages, but C# will protect you from doing it, so it's not necessary there.

like image 91
Rex M Avatar answered Oct 02 '22 16:10

Rex M


It's a holdover from C where older compilers would not catch this:

if (foo = null)

when you mean this:

if (foo == null)

The classic joke example is this mistake:

if (fireTheNukes = true)
    fireTheNukes();

This is generally accepted as an archaic pattern as any compiler worth its salt will catch an assignment within a conditional statement. I would avoid this pattern in your code as it serves no purpose these days.

like image 30
Andrew Hare Avatar answered Oct 02 '22 16:10

Andrew Hare