-2

How to hold Derived class list objects in Base class list object

class Base 
{
}

class Child : Base 
{
}

Base obj = new Child();

Will the same work for list.

List<Base> obj = new List<Child>(); 

This is giving me error, what is the best way to achive this.

BJ Myers
  • 6,617
  • 6
  • 34
  • 50
Harish kakani
  • 133
  • 1
  • 13

1 Answers1

0

Just because Child and Base have an implicit conversion, doesn't mean List<Child> and List<Base> do as these are now List<> objects.

List<Base> = (List<Base>)(new List<Child>())

You need to cast the child list to the parent list.

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42