2

I'm new to C# and I'm trying to create a custom key for a dictionary.

Here is how I create the class

public class ImageKey
{
    public int RId;
    public int EId;
    public int LId;

    public ImageKey(int rId, int eId, int lId)
    {
        RId = rId;
        EId = eId;
        LId = lId;
    }


    public bool Equals(ImageKey x, ImageKey y)
    {
        return x.RId == y.RId && x.LId == y.LId &&
              x.EId == y.EId;
    }

    public int GetHashCode(ImageKey obj)
    {
        int hash = 13;
        hash = (hash * 7) + obj.RId.GetHashCode();
        hash = (hash * 7) + obj.EId.GetHashCode();
        hash = (hash * 7) + obj.LId.GetHashCode();
        return hash;
    }

}

I use it as a hashset like that

HashSet<ImageKey> resourcesId = new HashSet<ImageKey>();

and as a Dictionary

var enteries = new Dictionary<ImageKey, int>();

but this statement fails for ContainsKey when I iterate over and try to see if there is a matched key

ImageKey key = new ImageKey(rId, eId, lId);
bool knownId = enteries.ContainsKey(key);
if (!knownId)
{
   enteries.Add(key, new IgaEntry());
}
andre_lamothe
  • 2,171
  • 2
  • 41
  • 74

1 Answers1

4

You class needs to override object.Equals, Implement IEquatable<T> interface, or implement IEqualityComparer<T> and pass it as a keyComparer to Dictionary's constructor. Also you need to override GetHashCode method to avoid unexpected behavior, make sure you do it right

Otherwise, your class will be compared by reference.

Refer Marc's answer here for a sample.

Community
  • 1
  • 1
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189