Properly checking for nulls

B

Brett Romero

What is a better way for checking nulls than using the "==" operator?
For example, .Equals() is better than == for most operations since it
knows the type being checked. However, it doesn't seem to work for
nulls. For example:


object myobject = new object();
myobject = null;
if (myobject.Equals(null))
Debug.WriteLine("no go");

For some reason, I get stuck on the if statement when debugging.
Stepping over just keeps me on the if line. Any suggestions?

Thanks,
Brett
 
A

Andy

== null is the way you are supposed to check for nulls..

..Equals is failing you because its trying to use null to determine
type, but getting the type of a null value results in an exception.
However, Equals swallows all exceptions.

BTW, using .Equals isn't better, and there's no reason to use it over
the == operator. I found its rare to compare two values of differing
types anyway.
 
B

Brett Romero

..Equals() is better in the case of non nulls. == has no idea what you
are comparing. It could be value or reference types and then system or
custom types. .Equals() doesn't have this issue. You'll notice the
parameter accepts the type you are calling the method on.

Brett
 
A

Andy

== knows exactly what you are comparing, because it is an operator
defined in a type. == will give you a compiler error if you try to
compare a Guid with a double, for example. Give it a shot.

Also, unless a reference type overrides the default implementation of
Equals, Equals will only return true if the object references are the
same (they are the EXACT same object).

To answer your orginal question, no, there is no other way to test for
null except using ==.

I don't know why you'd want to ignore type when comparing values
anyway. What exactly does it mean for one Stream object to equal a
Guid? It doesn't make sense, which is why == is a defined operator
between the two.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top