Can you add a ComplexType as a Key in a Dictionary()?

Yes. Technically it is possible. As long as the object references that are passed to the keys of the dictionary are not equal (meaning they're new instances of the type T), a dictionary can accept them without any exception.


class A
{
  public virtual int Add()
  {
    return 5 + 4;
  }
}
    
Dictionary<A, int> dict = new Dictionary<A, int>();
for (int i = 0; i < 10; i++)
{
    dict.Add(new A(), i);
}

foreach (var kv in dict)
{
    Console.WriteLine($"{kv.Key} => {kv.Value}");
}

Yes. Technically it is possible. As long as the object references that are passed to the keys of the dictionary are not equal (meaning they’re new instances of the type T), a dictionary can accept them without any exception.


class A
{
  public virtual int Add()
  {
    return 5 + 4;
  }
}
    
Dictionary<A, int> dict = new Dictionary<A, int>();
for (int i = 0; i < 10; i++)
{
    dict.Add(new A(), i);
}

foreach (var kv in dict)
{
    Console.WriteLine($"{kv.Key} => {kv.Value}");
}

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 *