Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading