Ahmad
Ahmad

Reputation: 24947

Have I changed the intent of the overridden `==` operator?

The following overloaded ==operator is part of the Calender class in QL.net

    public static bool operator ==(Calendar c1, Calendar c2)
    {
        return (c1.empty() && c2.empty()) 
                || (!c1.empty() && !c2.empty() && c1.name() == c2.name());
    }

    public bool empty() { return (object)calendar == null; }    

When I try to access the SouthAfricanCalender property, I receive a System.NullReferenceException : Object reference not set to an instance of an object. which prompted me to dig into the source.

public SouthAfrica SouthAfricanCalender
{
    get
    {
        if (_calender == null)
        {
        _calender = new SouthAfrica();
        }
    return _calender;
    }
    set
    {
        if (_calender == null)
        { 
        _calender = value;
        }
    }
}

SouthAfrica _calender;

I have ammended the overload as follows based on the answer here

public static bool operator ==(Calendar c1, Calendar c2)
{
   if ( object.ReferenceEquals(c1,c2)) return true;
   if ((object)c1 == null || (object)c2 == null) return false;

   return (c1.empty() && c2.empty())
       || (!c1.empty() && !c2.empty() && c1.name() == c2.name());
}

My question, have I changed the intent of the original code with my amendment?

Edit: any suggestions on how this can be cleaned up further?

Upvotes: 3

Views: 157

Answers (2)

Puppy
Puppy

Reputation: 147036

No. You ensure that both are objects, and respond accordingly in the places that they aren't (assuming that ReferenceEquals can handle double null). Then you simply execute the same check. The whole .empty() thing is totally unnecessary, by the way, you already know that it's not null, just return the name comparison.

Upvotes: 1

SLaks
SLaks

Reputation: 888223

No, you haven't.

It still checks for equality.

Upvotes: 1

Related Questions