2

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 ==.

2
  • I'm not going to post this as an answer because I'm too lazy to test it, but could you reverse the logic and use != ? Commented Dec 23, 2008 at 17:14
  • If you override ==, you also need to override !=. This could result in some circular logic. Commented Dec 23, 2008 at 17:15

6 Answers 6

7
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.)

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Thanks a lot james, i pasted solution i implemented in answers
1

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.

Comments

0

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; }
}

Comments

0

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.

Comments

0

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

Comments

0

I implemented the following and it 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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.