0

got actually a problem, I need to store a list of a class that need a generic type, but when inherited and generic type defined on a subclass, I can't add this subclass to the list anymore. Let me show you :

public class Foo<T>
{

}

public class Foo2 : Foo<int>
{

}

List<Foo<object>> objects = new List<Foo<object>>();
objects.Add(new Foo2()); // <----- This isn't working 

What is the way to do this ? Thanks for your time

Elytes
  • 51
  • 1
  • 4
  • AFAIK, there is no way to achieve that. This is because the class implements `Foo` and not `Foo`, inheritance happens on level of `Foo<>` not `T`. Maybe those classes could have a common interface instead? Something like `Foo : ISomething` ? – MaLiN2223 Jul 05 '20 at 22:01
  • So the only way to do this is to remove generic type and casting it ? – Elytes Jul 05 '20 at 22:02
  • In short - you can't. In some cases something similar would be achievable with [variance](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/creating-variant-generic-interfaces) and interfaces (though `Foo2` should be `Foo` of some reference type, not value type). – Guru Stron Jul 05 '20 at 22:04
  • That's not that stupid, I think i'm gonna use an interface that will be the best idea, thanks ! :D – Elytes Jul 05 '20 at 22:05
  • Also: https://stackoverflow.com/questions/58247604/how-to-do-generic-polymorphism-on-open-types-in-c/58247676#58247676 –  Jul 05 '20 at 22:07

0 Answers0