-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,339
  • 6
  • 37
  • 47
Harish kakani
  • 123
  • 1
  • 12

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,081
  • 3
  • 18
  • 38