dimanche 14 juillet 2019

Nested classes with inheritance tree in reverse order of outer classes in C#

I have read about when it's desired to use nested classes. But what isn't clear to me is how and why C# is built to cope with inheritance of nested types in the below way.

Let's say we have a outer class with nested class.

class OuterA
{
    internal class Nested
    {
    }
}

We then create a second outer class that inherits from the first one and has its own nested class. The new keyword is required because we hide OuterA.Nested. A virtual method is provided.

class OuterB : OuterA
{
    internal new class Nested 
    {
        public virtual int X => 1;
    }
}

We can now change OuterA.Nested to inherit OuterB.Nested and overrides its method.

internal class Nested : OuterB.Nested
{
    public override int X => 2; // I override a method of a class that hides me
}

I find it interesting that this is allowed. The order of inheritance of the outer classes is the inverse of that of the nested classes, yielding this peculiar way of defining OuterB.Nested.

internal new class Nested // I hide a class that overrides my method
{
    public virtual int X => 1;
}

Is this pattern useful or is it a mere edge case of the compiler?





Aucun commentaire:

Enregistrer un commentaire