0

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.

balixss
  • 11
  • 3
  • Outer is not an Inner, and you can never force it to become an Inner when it isn't an Inner. The contents are irrelevant. – Bent Tranberg Nov 16 '21 at 19:31
  • It's a lot easier if you name things `Base` and `Sub`, btw. A variable of type `Outer` can refer to an instance of an `Outer` or to an instance of any subclass of `Outer` (in this case, `Inner`). But, `Inner` is a _specialization_ of `Outer`, so a variable of `Inner` can only refer to an `Inner` object (or any subclasses of `Inner`). Just because `Inner` doesn't do anything special while it's specializing `Outer`, doesn't mean it's not a specialization. Consider the case where you have what you have, and it compiles, but then you add a member to `Inner`. It would suddenly break – Flydog57 Nov 16 '21 at 19:31
  • Yes, the names are super confusing. If just playing around learning C#, I'd suggest experimenting with a class hierarchy named like e.g. Animal -> Insect -> Butterfly – Bent Tranberg Nov 16 '21 at 19:39

1 Answers1

3

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.

Adam B
  • 3,662
  • 2
  • 24
  • 33