Amit
Amit

Reputation: 7035

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?
   }
}

Upvotes: 2

Views: 145

Answers (3)

Uatec
Uatec

Reputation: 141

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.

Upvotes: 0

Rogier van het Schip
Rogier van het Schip

Reputation: 937

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.

Upvotes: 1

christopher
christopher

Reputation: 27346

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.

Upvotes: 5

Related Questions