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