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.
if((object)left == null)
or if(ReferenceEquals(left, null))
. The former is perhaps more performant.
Feb 27, 2009 at 5:11
return right.Equals(left);
and then the code will crash if the right
student is null
(myobject == null
).
Feb 25, 2016 at 15:41
null == student
and student == null
will still invoke the overridden ==
operator, regardless of the operand order. So this answer looks wrong to me.
Jul 8, 2016 at 6:58
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.
if (wasEnabled == isEnabled()) ...
Feb 19, 2011 at 15:34
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.
For those who miss it, of if you're looking to reduce clutter, it's also possible to enable C-language
-style null-checking for your C#
classes:
class MyObj
{
public void implicit_null_comparison_demo()
{
MyObj mo = null;
// ...
if (mo) // <-- like so (can also use !mo)
{
// it's not null...
}
else
{
// it's null...
}
}
public static implicit operator bool(MyObj mo)
{
return (Object)mo != null;
}
};
=
is mistakenly used instead of equality testing ==
, which C#--unlike C and C++--normally flags as a syntax error.
Apr 5, 2019 at 17:05
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.