1

I have a situation where I would need a dictionary with this type of key, but it doesn't seem to find the equivalent key later on.

Dictionary<Tuple<int[], int>, object> cache = new Dictionary<Tuple<int[], int>, object>();

cache.Add(Tuple.Create(new int[]{1}, 1), new object());

Assert.That(cache.ContainsKey(Tuple.Create(new int[] { 1 }, 1))); // This fails

I've tested it by using a Tuple<int, int> and it seems to be working fine, but in my case I really need some sort of Tuple<int[], int> and with that type of key, it doesn't work.

Is there any other alternative to this that would be working?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Samuel Poirier
  • 1,240
  • 2
  • 15
  • 30

2 Answers2

9

Arrays are not comparable. For example:

var array1 = new int[] { 1 };
var array2 = new int[] { 1 };
Debug.WriteLine(array1 == array2); // this returns false
Debug.WriteLine(Object.Equals(array1, array2)) // this returns false

You need to do one of two things:

1) Replace int[] with a custom class that implements the necessary Equals and GetHashCode overrides.

2) Write a class that implements IEqualityComparer<Tuple<int[], int>>. That class will provide the Equals and GetHashCode methods for Tuple<int[], int>s. Provide an instance of that class to your Dictionary<Tuple<int[], int>, object>

Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
0

You can not compare array with == You can use this code:

 static bool ArraysEqual<T>(T[] array1, T[] array2)
    {
        if (ReferenceEquals(array1,array2))
            return true;

        if (array1 == null || array2 == null)
            return false;

        if (array1.Length != array2.Length)
            return false;

        EqualityComparer<T> comparer = EqualityComparer<T>.Default;
        for (int i = 0; i < array1.Length; i++)
        {
            if (!comparer.Equals(array1[i], array2[i])) return false;
        }
        return true;
    }
Community
  • 1
  • 1