serge
serge

Reputation: 15239

Implementing IEqualityComparer

I've added to my class the IEqualityComparer implementation, not sure if the code bellow is the correct one, especially the Equals(object x, object y) functions: should we override or make a new implementation of the Equals method, like this: ?

public class PropertySettings : IEqualityComparer
{
    public int? Precision { get; set; }
    public double? Min { get; set; }
    public double? Max { get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null || !(obj is PropertySettings))
            return false;

        var ps = obj as PropertySettings;

        return
            ps.Precision == this.Precision &&
            ps.Min == this.Min &&
            ps.Max == this.Max;
    }

    public bool Equals(object x, object y)
    {
        if (x != null && x is PropertySettings)
            return x.Equals(y);
        else
            return object.Equals(x, y);
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Precision, Min, Max);
    }

    public int GetHashCode(object obj)
    {
        if (obj == null)
            return 0;
        if (obj is PropertySettings)
            return (obj as PropertySettings).GetHashCode();
        else
            return obj.GetHashCode();
    }
}

enter image description here

Upvotes: 0

Views: 1542

Answers (1)

David
David

Reputation: 236

According to the IEqualityComparer code example provided by microsoft, you will want to use the new keyword (so hiding the Equals implementation of the object) for implementing Equals.

https://learn.microsoft.com/en-us/dotnet/api/system.collections.iequalitycomparer.equals?view=net-6.0#system-collections-iequalitycomparer-equals(system-object-system-object)

As pointed out by Jeroen Mostert below, these can be incorrect. His recommendation of implementing IEqualityComparer.Equals works as well. You can also use override. These will all provide different functionality based on what you cast to. Here is a brief explanation:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords

Basically, using override would mean that you will use your .Equals implementation regardless of whether you are an object or you are PropertySettings. If you use new when you are an object you will use the base .Equals(... functionality (that of object in this case). If you explicitly implement IEqualityComparer.Equals(... then you will use the .Equals when you cast your object as an IEqualityComparer. This leaves you with the choice of how you are using your class.

Upvotes: 0

Related Questions