0

I have a class with KeyValuePair, following implementation of IEquatable does not work as I expected. and my unit test fails. I want to know why test fails?

class:

public class MyClass : IEquatable<MyClass>
{
    public KeyValuePair<int[], string> KeyValuePair { get; set; }

    public override bool Equals(object obj)
    {
        return Equals(obj as MyClass);
    }

    public bool Equals(MyClass other)
    {
        return other != null &&
               EqualityComparer<KeyValuePair<int[], string>>.Default.Equals(KeyValuePair, other.KeyValuePair);
    }

    public override int GetHashCode()
    {
        var hash = new HashCode();
        hash.Add(KeyValuePair);
        return hash.ToHashCode();
    }
}

Test:

[Fact]
    public void Test1()
    {
        MyClass expectedObject = new MyClass()
        {
            KeyValuePair = new KeyValuePair<int[], string>(new int[] { 1 }, "abc")
        };
        MyClass actualObject = new MyClass()
        {
            KeyValuePair = new KeyValuePair<int[], string>(new int[] { 1 }, "abc")
        };
        Assert.Equal(expectedObject, actualObject);
    }

test result:

Message: Assert.Equal() Failure

Mojtaba Khooryani
  • 1,763
  • 1
  • 17
  • 36
  • It depends what's inside the `new HashCode();`? – Salah Akbari Jul 22 '19 at 09:42
  • 1
    it's obviously becuase `int[]` as `new int[] {1}.Equals(new int[] {1})` [would return false](https://dotnetfiddle.net/mwCmFq) – Selvin Jul 22 '19 at 09:46
  • A key must be a singleton and not an array. Your KeyValuePair has a key int[] which is an array. – jdweng Jul 22 '19 at 09:57
  • @jdweng singleton? not true ... https://dotnetfiddle.net/oaxl45 it have to have implementation of Equals other than simple reference comparsion – Selvin Jul 24 '19 at 12:07
  • You do not have an array. Your keys are strings. The string.format is under the hood creating an output string (not an array) : string.Format("ab{0}",'c'); – jdweng Jul 24 '19 at 12:21

1 Answers1

0

You did not go deep enough with your Equals() implementation. Because:

Console.WriteLine("Are two int[] arrays equal? => "+
     EqualityComparer<int[]>.Default.Equals(new int[] { 1 }, new int[] { 1 }));

Console.WriteLine("Do two int[] have the same hashcode? => " +
     (new int[] { 1 }.GetHashCode() == new int[] { 1 }.GetHashCode()));

Are two int[] arrays equal? => False

Do two int[] have the same hashcode? => False

You'd have to implement the Equals() and GetHashCode() logic for int[] array too, e.g.:

public class EquatableIntArray : IEquatable<EquatableIntArray>
{
    public int[] Items { get; set; }

    public EquatableIntArray(int[] Items)
    {
        this.Items = Items;
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as EquatableIntArray);
    }

    public bool Equals(EquatableIntArray other)
    {
        if (other == null) return false;
        if (ReferenceEquals(this, other)) return true;
        return other.Items != null && (this.Items?.SequenceEqual(other.Items)??false);
    }

    private int? cachedHashCode;

    public override int GetHashCode()
    {
        if (cachedHashCode.HasValue) return cachedHashCode.Value;
        int hc = Items.Length;
        for (int i = 0; i < Items.Length; ++i)
        {
            hc = unchecked(hc * 314159 + Items[i]);
        }
        return (cachedHashCode = hc).Value;
    }
}

(above implementation of GetHashCode() from here)

Console.WriteLine("Are two EquatableIntArrays equal? => " +
     EqualityComparer<EquatableIntArray>.Default.Equals(
         new EquatableIntArray(new int[] { 1 })
       , new EquatableIntArray(new int[] { 1 })));

 Console.WriteLine("Do two EquatableIntArrays have the same hashcode? => " +
      (new EquatableIntArray(new int[] { 1 }).GetHashCode()
    == new EquatableIntArray(new int[] { 1 }).GetHashCode()));

Are two EquatableIntArrays equal? => True

Do two EquatableIntArrays have the same hashcode? => True

Then, in your class you'll have something like this:

public class MyClass2 : IEquatable<MyClass2>
{
    public KeyValuePair<EquatableIntArray, string> KeyValuePair { get; set; }

    public override bool Equals(object obj)
    {
        return Equals(obj as MyClass2);
    }

    public bool Equals(MyClass2 other)
    {
        return other != null &&
               EqualityComparer<KeyValuePair<EquatableIntArray, string>>.Default.Equals(KeyValuePair, other.KeyValuePair);
    }
    private int? cachedHashCode;
    public override int GetHashCode()
    {
        if (cachedHashCode.HasValue) return cachedHashCode.Value;
        cachedHashCode = CombineHashCodes(KeyValuePair.Key.GetHashCode(), KeyValuePair.Value.GetHashCode());
        return cachedHashCode.Value;
    }

    internal static int CombineHashCodes(int h1, int h2)
    {
        return (((h1 << 5) + h1) ^ h2);
    }
}

(I tested on .NET Framework 4.7, and there's no HashCode class there, so I borrowed the GetHashCode() implementation from Tuple)

And:

MyClass2 expectedObject2 = new MyClass2()
{
  KeyValuePair = new KeyValuePair<EquatableIntArray, string>(new EquatableIntArray(new int[] { 1 }), "abc")
};
MyClass2 actualObject2 = new MyClass2()
{
   KeyValuePair = new KeyValuePair<EquatableIntArray, string>(new EquatableIntArray(new int[] { 1 }), "abc")
};

Console.WriteLine("Are two MyClass2 instances equal? => "+ expectedObject2.Equals(actualObject2));

Are two MyClass2 instances equal? => True

Arie
  • 5,251
  • 2
  • 33
  • 54