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 appears that the nested class is "inherited" by the subclass. Where's the point in that? What can I do with this feature that I cannot (or cannot easily) do otherwise? Aren't Outer.Nested
and SubOuter.Nested
exactly equivalent?
Clarification: Of course it compiles because the C# spec says so. I understand that. I am asking why C# was designed that way, since it does not seem to add something to the language. If you have an example to the contrary, i.e., some code that gets easier/shorter/better by using this feature, please share it in an answer and I will gladly accept it.
From the perspective of Test
Nested
is just an identifier as if it were a member e.g. As it is public
You may access it everywhere where you cann access any of the classes Outer
or SubOuter
. However both usages are identical, they identify the same class.
You may even reference the one by the 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 may see in the debugger both x
and y
share a reference to Outer.Nested
instead of SubOuter.Nested
.
EDIT: As other already mentioned this is no new feature, it is simply the usual treating of members within classes. Thus it surely does not add any benefit to the language as the feature as you describe it simply does not exist. This therefor follows the Principle of least astonishment.
Treating nested classes differenetly however would be a new feature.
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