Home > Software design >  C# Dictionary can't find Key of type HashSet<enum>
C# Dictionary can't find Key of type HashSet<enum>

Time:04-23

private Dictionary<HashSet<Flags>, int> dict;

The dictionary is populated at Start using the Unity inspector

public enum Flags
{
    flag1,
    flag2,
    flag3
}

Iterating the dictionary confirms it contains the same hashset being used to access, but attempting to access with the key always returns a KeyNotFoundException. Manually testing with ContainsKey also returns false.

CodePudding user response:

Well, .Net by default compare classes by references, e.g.

// A and B has same values, but different references
var A = new HashSet<Flags>() { Flags.flag1 };
var B = new HashSet<Flags>() { Flags.flag1 };

// Not Equals, since A and B doesn't share the same reference:
if (A.Equals(B)) 
  Console.Write("Equals");
else
  Console.Write("Not Equals");

If you want to compare by values, you should implement IEqualityComparer<T> interface:

    public class HashSetComparer<T> : IEqualityComparer<HashSet<T>> {
      public bool Equals(HashSet<T> left, HashSet<T> right) {
        if (ReferenceEquals(left, right))
          return true;
        if (left == null || right == null)
          return false;

        return left.SetEquals(right);
      }

      public int GetHashCode(HashSet<T> item) {
        return item == null ? -1 : item.Count;
      }
    }

And use it:

private Dictionary<HashSet<Flags>, int> dict = 
  Dictionary<HashSet<Flags>, int>(new HashSetComparer<Flags>());
  • Related