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?
The second stems from C/C++ (and elsewhere) where this is a valid construct
That’s not valid in C# (unless your expression resolves to a boolean). For example, this is valid C#
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.