null and overloading == operator

A

Andrew Gniadek

hey,
if i overload the == operator then i have problems with checking if a
reference to an object is null. just wondering how i can get away with
it. because as soon as I overload it then i can't check for a null
reference within that implementation cuz it gets recursively called
resulting in a stack overflow.
operator overloading is still rough waters for me. mostly worked in java
so never had that option.
appreciate any help, thx.
A.
 
J

Jon Skeet [C# MVP]

Andrew Gniadek said:
if i overload the == operator then i have problems with checking if a
reference to an object is null. just wondering how i can get away with
it. because as soon as I overload it then i can't check for a null
reference within that implementation cuz it gets recursively called
resulting in a stack overflow.
operator overloading is still rough waters for me. mostly worked in java
so never had that option.

Either cast one or both sides to null to get identity comparison, or
use Object.ReferenceEquals.
 
B

Bryan

You could put it in a try..catch block and just catch the
NullPointerException that occurs if you reference the null.
 
J

Jon Skeet [C# MVP]

Bryan said:
You could put it in a try..catch block and just catch the
NullPointerException that occurs if you reference the null.

Yikes - while I'm not one of those who advocates avoiding exceptions at
all costs, that's a really horrible way of doing things. There are much
better solutions in this case, just as there's almost *always* a better
solution to avoiding a NullReferenceException than just catching it.
 

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