Why are nested classes "inherited"?

Consider the following code example:

class Outer { public class Nested { } } class SubOuter : Outer { } class Test { Test() { Outer.Nested x; // Makes sense. SubOuter.Nested y; // Compiles, but why? } } 

It seems that the nested class is "inherited" by a subclass. Where is the point? What can I do with this function, which I cannot (or cannot easily) do otherwise? Not equivalent to Outer.Nested and SubOuter.Nested ?

Explanation . Of course, it compiles because the C # specification says so. I understand it. I ask why C # was designed this way, as it does not seem to add anything to the language. If you have an example to the contrary, that is, some code that is becoming simpler / shorter / better using this function, please share it in response, and I will be happy to accept it.

+5
source share
2 answers

From the point of view of Test Nested this is just an identifier, as if it were a member, for example. Since this is public , you can access it wherever you can access any of the Outer or SubOuter . However, both methods are identical; they identify the same class.

You can even refer to each other:

 Outer.Nested x = new Outer.Nested(); SubOuter.Nested y = x; 

Or even

 Outer.Nested x = new SubOuter.Nested(); SubOuter.Nested y = x; 

However, as you can see in the debugger, x and y use the Outer.Nested link instead of SubOuter.Nested .

EDIT: as already mentioned, this is not a new feature, it is just the usual handling of members within classes. Thus, it certainly does not add any benefit to the language, since the function that you describe simply does not exist. From here follows the principle of least surprise .

The treatment of nested classes is different, however this will be a new feature.

+5
source

Since the class is Nested public , so the SubOuter class can see it in the base class.

And you are right. Outer.Nested and SubOuter.Nested equivalent, there are no differences, except for the declaration method.

Update

according to your comment that functions have costs. this function is already implemented in .NET (I mean that a subclass can see the public and protected members of the base class) so there is no additional cost to implement, this is .NET.

you can consider the Nested class like any other property in the base class.

It is very important to explain what is written in the comments to your question @Damien_The_Unbeliever.

No, you are asking for a new feature. All public members of the base class are accessible through class inheritance. Why should classes be handled differently than, for example, methods, and why should the compiler command specifically add code so that you cannot make such calls? (And then get an error message translated into various languages, write it down, etc.)

+3
source

Source: https://habr.com/ru/post/1240502/


All Articles