tags:

views:

842

answers:

4

Are these equivalent:

if (null==myobject)
{
//do something 
}

and

if (myobject==null)
{
//do something 
}

or will they produce different code?

+18  A: 

In the 99% case this code is equivalent.

The one exception is when the type of the object in question overrides the == operator. It's possible for a bug to be introduced in == which causes problems when one parameter is null.

A particular example I've seen before is the following

public static bool operator==(Student left, Student right) {
  return left.Equals(right);
}

This will fail when null is on the left, but likely not when null in on the right.

This is a pretty far out corner case though.

JaredPar
The solution is: `if((object)left == null)` or `if(ReferenceEquals(left, null))`. The former is perhaps more performant.
Justice
@Justice, I haven't ever investigated the JIT but if you do Object.Reference equals, C# will generate a method call. In the abscence of a operator== C# will generate a direct value comparison with the IL opcode ceq. My guess is the ceq is faster.
JaredPar
@Justice, but don't ever assume anything about performance, trust the profiler :)
JaredPar
+6  A: 

The form of "if" statement that puts the constant at the left is a holdover from C/C++ where you could have an arbitrary expression in an if statement.

C#'s syntax for if statements requires that the expression evaluate to a bool which means that if (foo = 0) won't compile.

Larry Osterman
Oh good. I was remembering back a couple of years ago, when I was learning C#, and I'd sworn I recalled getting a compiler warning or error when using assignment (by accident) in an if statement, along with other safety devices (such as a missing break in a switch statement). +1
Devin Jeanpierre
A: 

As pointed out by others they are mostly equivalent.

You should also take a look at: http://en.wikipedia.org/wiki/Null_Object_pattern

It is a very useful alternative to simply checking for a null reference.

codeelegance
+2  A: 

The

if (null==myobject) {

is a safe way of writing an if statement. It comes from C/C++ where the condition is an expression evaluated to an int. If the result is zero that means false, anything else is true. You could write something like

if (variable == 1) {

but if you weren’t careful you could also write

if (variable = 1) {

in which case you have an assignment that always evaluates to 1 and thus is always true.

You could compile this and run it with no problems, but the result wouldn’t be what you expected. So C/C++ programmers started to write things like

if (1 == variable) {

This won’t compile if you misspell it, so you always had to write it as you meant to write it. This later becomes a (good) habit and you use it in all the languages you program with, C# for example.

dpb