Can you add a ComplexType as a Key in a Dictionary<T, int>()?

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

C# Concepts Posted May 14, 2021

You can now show your support. 😊

We use cookies to provide you with a great user experience, analyze traffic and serve targeted promotions.   Learn More   Accept