Can I create a Dictionary with a Complex Type as a Key? If Yes How?

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

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

Default image
Sriram Mannava

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity.

Leave a Reply