Overloading operator== and comparing to null

P

Paul Lyons

Not sure how I've not come across this before...

I've overloaded operator == for one of my classes using
the following code.

public static bool operator ==(Stock x, Stock y)
{
return x.Equals(y);
}
public override bool Equals(object obj)
{
Stock queryObject = null;
if (obj is Stock)
queryObject = (Stock) obj;
else
return false;

return ((queryObject.StockCode == this.StockCode));
}

In another class I have the following code:

private Stock _stock = null;
private Stock getStock()
{
if (_stock == null) // Error here...
{
_stock = new Stock()
// populate details
}
}

My error occurs, because I initialise my local copy to
null, so it has no methods...
How do I check whether or not my object is null??

Thanks in advance
Paul
 
J

Jack Hanebach

public static bool operator ==(Stock x, Stock y)
{
return x.Equals(y);
}

you need to check if x is not null

if (x == null)
return y == null;
else
return x.Equals(y);
 
C

Christoph Nahr

you need to check if x is not null

if (x == null)
return y == null;
else
return x.Equals(y);

Watch out for a nasty trap here. Your code will result in an infinite
recursion because (x == null) invokes the strongly typed overload of
operator== which is currently executing.

You have to use a System.Object comparison instead, such as:

if ((object) x == null)
return ((object) y == null);
else
return x.Equals(y);
 
J

Jack Hanebach

Watch out for a nasty trap here. Your code will result in an infinite
recursion because (x == null) invokes the strongly typed overload of
operator== which is currently executing.

You have to use a System.Object comparison instead, such as:

if ((object) x == null)
return ((object) y == null);
else
return x.Equals(y);

Good catch! I guess if (null == x) would work too...
 
J

Jon Skeet

Jack Hanebach said:
Good catch! I guess if (null == x) would work too...

No, that would still call the overloaded == operator. See section
14.2.4 of the C# specification - the order isn't taken into account
when selecting the operator implementation to use.

I'd also argue that even if it *did* work, it would be a bad way of
doing it, as anyone just looking at it might not realise the purpose of
specifying the operator that particular way, and change it to the more
natural (in English) if (x==null). Fortunately, that's not an issue
anyway :)
 

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