Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I check to see if an object is null first or second? [duplicate]

Tags:

c#

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?

like image 824
bendewey Avatar asked Mar 24 '09 21:03

bendewey


People also ask

Should you always check for NULL?

The best way is to only check when necessary. If your method is private , for example, so you know nobody else is using it, and you know you aren't passing in any nulls, then no point to check again. If your method is public though, who knows what users of your API will try and do, so better check.

How do you check if a list is empty or null?

isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.


1 Answers

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.

like image 108
cletus Avatar answered Oct 20 '22 00:10

cletus