tags:

views:

182

answers:

6

I am trying to write operator overload for custom class and don't know how to handle null comparison.

Class Customer
{
    int id;

    public static bool operator ==(Customer a, Customer b)
    {
        //When both a and b are null don't know how to compare as can't use == in here as
        //it will fall into loop
    }
}

Problem is when a and b both are null result is true but not sure how to check it without using ==.

+1  A: 

I'm not 100% sure I understand the problem, but you should be able to do:

if (((object)a == null) && ((object)b == null)) { return true; }

Without any problems.

Steven Robbins
+7  A: 
if (Object.ReferenceEquals(a,b))
     return true;

ReferenceEquals() checks if they are pointing to the exact same object (or if they are both null)

(As a general rule, it's good to start an Equals() method with a call to ReferenceEquals, particularly if the rest of the method is complicated. It will make things like a==a quickly return true, instead of having to check every element.)

James Curran
Now we just need to hear back from the OP to see if part of the override was to do something special if both objects were null. Otherwise, very nice solution.
EBGreen
Thanks a lot james, i pasted solution i implemented in answers
mamu
A: 

I usually use object.Equals(a, b).

In your case:

public static bool operator ==(Customer a, Customer b)
{
    if(object.Equals(a, null) && object.Equals(b, null)
    { return true; }
}
Albic
A: 

any of the following

 object.ReferenceEquals(a, null)
 object.Equals(a, null)
 (object)a == null;

PS. I think this is probably better off in Customer.Equals, and having == rely on that.

Jimmy
A: 

Is it possible to cast them to system.object and use the == operator to check if it's null? I'd check it but I'm not on a dev machine

Tarks
A: 

Thanks a bunch guys,

I implemented following and works like champ

public static bool operator ==(Customer a, Customer b)

{

if(object.ReferenceEquals(a,b)
{ return true; }
else if(((object)a == null) || ((object)b == null))
     {return false;}
else if(a.Id == b.Id)
     {return true;}

return false;

}

public static bool operator !=(Customer a, Customer b) { return !(a==b); }

mamu