I have the following code.
class Program
{
static void Main(string[] args)
{
Outer outer = new Outer();
Inner inner = new Inner();
Outer outer2 = new Inner();
Inner inner2 = new Outer();
}
}
public class Outer { }
public class Inner : Outer { }
I get the compiler error when assigning new Outer()
to inner2
because it's of type Inner
. I understand that it's to do with the inheritance but I can not figure out why because the contents are the same. Also, how can I force it to be cast to Inner
.
I have tried
(inner)new Outer();
new Outer() as Inner;
But it threw an exception about conversion in the former and became null in the latter. Not sure what to google for to find out. I mean like this but the exact opposite.
CodePudding user response:
A subclass is of type base class, but not the opposite. consider renaming them to
class Dog {}
class GermanShepard : Dog {}
This makes it clear that A German Sheppard is definitely a dog. But a dog is not necessarily a German Shepard.
writing the following is not possible, since the new dog could end up being another type of dog.
GermanShepard fred = new Dog(); //error!!
It might be a Shitzu or a Labrador. But you can always cast a German Shepard to a dog. Similarly you can always cast a Labrador to a dog.