6

Say for example that I create a Duck

Duck myDuck = DuckFactory.CreateDuck();

In the past I've always check to see if myDuck is null

if (myDuck == null)
{
  // Do stuff
}

I've recently looked at some code that check for null first.

if (null == myDuck)
{
   // Do stuff
}

It seems to me that these are the same, but are there any differences between these two? Is there any performance benefits to one over the other? Is there a recommended best practice for checking if an object is null?

bendewey
  • 39,709
  • 13
  • 100
  • 125
  • Dupie McDuperson: http://stackoverflow.com/questions/655657/0-variable-or-null-obj-an-outdated-practice-in-c/655670#655670 – Dana Mar 24 '09 at 21:41
  • Dupes of at least 3: http://askjonskeet.com/search/?q=typo+C%2B%2B – Jon Skeet Mar 24 '09 at 21:46
  • I tried to do my due diligence, searching for a dup on this. To me it was a very hard concept to verbalize in a concise fashion. Either way, thanks for the great responses. – bendewey Mar 24 '09 at 22:09
  • @bendewey: Absolutely, various questions are tricky to find, including this one. – Jon Skeet Mar 24 '09 at 22:14

5 Answers5

16

The second stems from C/C++ (and elsewhere) where this is a valid construct

if (myDuck = null) {
}

That's not valid in C# (unless your expression resolves to a boolean). For example, this is valid C#

bool b = ...
if (b = true) {
}

Putting the constant first was defensive to stop accidental assignment when you wanted comparison. I'd say more people put the variable to the left but there is nothing wrong with putting the constant to the left either.

Just pick one and be consistent about it.

cletus
  • 616,129
  • 168
  • 910
  • 942
1

The only difference occurs if you were to put this by accident:

if(myDuck = null) ...

But in reality, the C# compiler is smart enough to detect this.

If you put this by accident:

if(null = myDuck) ...

Then this would result in an error back in the C or C++ days.

Long story short: it makes no difference in C#.

John Rasch
  • 62,489
  • 19
  • 106
  • 139
1

Putting 'null' first prevents accidental assignment if (myDuck=null). However, some compilers throw an error when trying to do that, and therefore the point is moot. IMO it all comes down to style - pick one, and stick with it :)

0

I think there is no difference whatsoever.

The if-statement will simply check wheter or not the expression it contains is true. Wheter myDuck is to the left of the right of the == symbol makes no difference.

KdgDev
  • 14,299
  • 46
  • 120
  • 156
0

One looks like C++ syntax, the other like Java or C#.

From what I've read, The "null == myDuck" syntax originated in C from people accidently assigning in their if statements:

if (myDuck = null)
  // returns true
Chris S
  • 64,770
  • 52
  • 221
  • 239