0

Hi I want to make a list of generic class objects, but T of the generic class is dynamic. For example, I want to make a list which can contain SomeClass<int>, SomeClass<string>, SomeClass<char> etc...

class SomeClass<T>{}

List<SomeClass<dynamic>> list = new List<SomeClass<dynamic>>();
list.Add(new SomeClass<int>()); //CS1503 : cannot convert from 'SomeClass<int>' to 'SomeClass<dynamic>'
list.Add(new SomeClass<string>()); //CS1503 : cannot convert from 'SomeClass<string>' to 'SomeClass<dynamic>'
list.Add(new SomeClass<char>()); //CS1503 : cannot convert from 'SomeClass<char>' to 'SomeClass<dynamic>'
null
  • 29
  • 3
  • 1
    Maybe have a base class `SomeClass` and have `SomeClass` derive from it or an `ISomeClass` interface that `SomeClass` implements. That way, your list could be `List` or `List`. – 41686d6564 stands w. Palestine Jun 05 '21 at 12:52
  • The only types in C# that can unify `SomeClass` for an unconstrained `T` are `object` and `dynamic`. Note: not `SomeClass`; at runtime this is just `SomeClass`, and since reference-type generics and value-type generics have different representations, classes like `SomeClass` and `SomeClass` fundamentally can't be treated as the same type. – Jeroen Mostert Jun 05 '21 at 12:55
  • Does this answer your question? [How to create List of open generic type of class?](https://stackoverflow.com/questions/58570948/how-to-create-list-of-open-generic-type-of-classt) and [How to do generic polymorphism on open types](https://stackoverflow.com/questions/58247604/how-to-do-generic-polymorphism-on-open-types-in-c/) –  Jun 05 '21 at 13:03
  • [C# generic inheritance and covariance part 2](https://stackoverflow.com/questions/14263964/c-sharp-generic-inheritance-and-covariance-part-2/14264436#14264436) –  Jun 05 '21 at 13:08

0 Answers0