1

I have 2 classes:

abstract class Bar { }

class Foo<T> where T : Bar { }

and I want to to create a List of 'Foo's that can have different generic classes that are all inherited from 'Bar':

class NewBar : Bar { }

But I can not save the classes as Foo<Bar>:

Foo<Bar> variable = new Foo<NewBar>();

So what have I done wrong and how would this be possible?

Someone
  • 43
  • 8
  • 1
    `Foo` needs to be co-variant for this to work, which is `class Foo where ...`. See https://learn.microsoft.com/dotnet/csharp/programming-guide/concepts/covariance-contravariance/ for further details. – MakePeaceGreatAgain Dec 14 '17 at 11:54
  • 1
    What have you tried? There are tens, if not hundreds of questions that describe this. Keywords being "covariance" and "contravariance". – CodeCaster Dec 14 '17 at 11:55

0 Answers0