简体   繁体   中英

C# OOPS clarification

Please why line "b[0]= new Child2();" fails at runtime and not at compile time. Please don't check the syntax, i just did it here

class Base
{}

class Child1 : Base
{}

class Child2 : Base
{}

class Test
{
   void Main()
   {
     Base [] b= new Child1[10];
     b[0]= new Child2(); <-- Fails at runtime but not at compile time WHY?
   }
}
new Child1[10];

You've just declared a new array of type Child1 .

b[0]= new Child2();

Now you're attempting to put a sibling class, into it. An array of objects can store that object, and it's subclasses, but can not store it's siblings.

Ilya Ivanov is right: An array of Child1 objects can be cast to an array of Base objects. But you cannot add a Child2 to this, as this is a different class.

Array covariance means that if two classes have a subclass - superclass relationship, their arrays also have this relationship.

You defined b as array of child1, then are trying to insert a child2.

However the compiler cannot what you assigned to b, as anything could happen between the two lines. At runtime however, it can be determined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM