How to create a Dictionary with a Complex Type as a Key?

Yes you can. Dictionary can be created with a Complex Type as a Key and a simple type as a value.

Yes you can. Dictionary can be created with a Complex Type </T/> as a Key and a simple type as a value.

For example:

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);

The above code works without any issues. Because each object holds a different reference and hence the Keys are all different w.r.t the Dictionary


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 *