0
public class A
{

}
public class B:A
{

}
public class Program
{
    public static void Main(String[] args)
    {
        List<A> my = new List<B>();
    }
}

As we can store derived class's reference to base class reference. Here as the list is the array of references we should be able to store references as shown above. Please Clarify. Thanks in advance.

roopteja
  • 721
  • 2
  • 16
  • 36
  • 2
    Consider you could and imagine it's not `A` and `B` but `Animal` and `Giraffe`. Nothing prevents you to add also a `Tiger` to the list because it's also an animal, but it doesn't belong into the giraffe-list. A list is mutable, that's why it's dangerous (for the giraffes and you) if it would be allowed. With arrays it is allowed. Read [J. Skeet](https://stackoverflow.com/a/2033921/284240) – Tim Schmelter Sep 01 '17 at 10:15
  • Thank you Tim schmelter for the clarification. – roopteja Sep 01 '17 at 12:10

1 Answers1

0

You are meant to create a list of the parent class

List<A> my = new List<A>();

Then you can add B

my.Add(new B());
my.Add(new A());
FakeCaleb
  • 982
  • 8
  • 19