Search code examples
c#reflectionequality

C# Equals extension is unable to check equality


I extended the equals method and hashcode to check for equality of two identical objects with boolean properties. when I mutate the object making one of the boolean properties false instead of true it fails to recognize the difference and asserts they are equal;. Any Ideas why?

   public override bool Equals(object value)
    {
        if (!(value is LocationPropertyOptions options))
            return false;

        return Equals(options, value);
    }

    public bool Equals(LocationPropertyOptions options)
    {
        return options.GetHashCode() == GetHashCode();
    }

    public override int GetHashCode()
    {
        return ToString().GetHashCode();
    }

    public override string ToString()
    {
        return $"{Identifier}{AccountEntityKey}{Address}{Comments}{Contact}" +
               $"{Coordinate}{Description}{FaxNumber}{LastOrderDate}{PhoneNumber}" +
               $"{ServiceAreaOverride}{ServiceRadiusOverride}{StandardInstructions}" +
               $"{WorldTimeZone_TimeZone}{ZoneField}{CommentsOptions}";
    }

Solution

  • You cast options from value, then call Equals with options vs value. That means you compare value with value, it returns always true for you

    public override bool Equals(object value)
    {
        if (!(value is LocationPropertyOptions options))
           return false;    
        return Equals(options, value);
    }
    

    Try comparing this with value, like

    return Equals(this, value);