For example:
public class A : A.B { public class B { } }
Which generates this error from the compiler:
Circular base class dependency involving 'A' and 'A.B'
I always figured a nested class behaved just like a regular class except with special rules concerning accessing the outer class's private members, but I guess there's some implicit inheritance occurring between the two classes?
Just like static members, a static nested class does not have access to the instance variables and methods of the outer class. You can extend static inner class with another inner class.
A static nested class can inherit: an ordinary class. a static nested class that is declared in an outer class or its ancestors.
A class can be nested up to any depth; there is no practical limit, but a class nested deeper that two is almost always unnecessary.
And the benefit of it is you can have less number of objects created at runtime which wouldn't be the case with other types of nested classes. Disadvantage The only disadvantage I can think of is a static nested class has access to both the protected and private members of the outer class.
There's no implicit inheritance involved as far as I can tell. I would have expected this to be okay - although I can imagine weirdness if A and B were generic.
It's specified in section 10.1.4 of the spec:
When a class B derives from a class A, it is a compile-time error for A to depend on B. A class directly depends on its direct base class (if any) and directly depends on the class within which it is immediately nested (if any). Given this definition, the complete set of classes upon which a class depends is the transitive closure of the directly depends on relationship.
I've highlighted the relevant section.
That explains why the compiler is rejecting it, but not why the language prohibits it. I wonder if there's a CLI restriction...
EDIT: Okay, I've had a response from Eric Lippert. Basically, it would be technically possible (there's nothing in the CLI to prohibit it), but:
It was also noted on the email thread that it would make this kind of thing valid:
A.B x = new A.B.B.B.B.B.B.B.B.B.B.B.B();
... but that would already (as noted by Tinister) be valid if B derived from A.
Nesting + inheritance = oddness...
This is not a C# thing as much as it is a compiler thing. One of the jobs of a compiler is to lay out a class in memory, that is a bunch of basic data types, pointers, function pointers and other classes.
It can't construct the layout for class A until it knows what the layout of class B is. It can't know what the layout of class B is until it finished with the layout of class A. Circular dependency.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With