Are these equivalent:
if (null==myobject)
{
//do something
}
and
if (myobject==null)
{
//do something
}
or will they produce different code?
Are these equivalent:
if (null==myobject)
{
//do something
}
and
if (myobject==null)
{
//do something
}
or will they produce different code?
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.
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.
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.
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.