How do you ensure that the Dictionary Keys are Unique in case of Complex Type Keys?

For example if we have a Dictionary defined as:

class MyClass { 
  public MyClass(int id) { 
    this.Id = id 
  }
  public int Id { get; set; }
}

Dictionary<MyClass, int> dict = new Dictionary<MyClass, int>();
dict.Add(new MyClass(1), 1);
dict.Add(new MyClass(2), 2);
dict.Add(new MyClass(3), 3);

To ensure that the Keys are always unique, we need to implement the GetHashCode() method for the MyClass which by default extends the System.Object class. This is the method that the Dictionary internally uses to compute HashKey for the Keys.

For example if we have a Dictionary defined as:

class MyClass { 
  public MyClass(int id) { 
    this.Id = id 
  }
  public int Id { get; set; }
}

Dictionary<MyClass, int> dict = new Dictionary<MyClass, int>();
dict.Add(new MyClass(1), 1);
dict.Add(new MyClass(2), 2);
dict.Add(new MyClass(3), 3);

To ensure that the Keys are always unique, we need to implement the GetHashCode() method for the MyClass which by default extends the System.Object class. This is the method that the Dictionary internally uses to compute HashKey for the Keys.


Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *