Nested types in C# have the ability to access the parent's private properties. Is there a specific reason for having this language feature ? In my opinion this breaks encapsulation. If I make the nested type public, then I would be able to expose private properties of parent class through it.
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
A nested type has access to all of the members that are accessible to its containing type. It can access private and protected members of the containing type, including any inherited protected members.
In C#, a user is allowed to define a class within another class. Such types of classes are known as nested class. This feature enables the user to logically group classes that are only used in one place, thus this increases the use of encapsulation, and create more readable and maintainable code.
The contained, inner class is called a nested class, and the class that contains it is called, simply, the outer class. Nested classes have the advantage of access to all the members of the outer class. That is, a method of a nested class can access private members of the outer class.
You would be able to - but you can only nest the class if you've got it in the same source file as the outer class in the first place.
Effectively the nested class is "owned" by the outer class, and trusted to the same extent as any other member of the outer class. A method in the outer class could expose a private property too - but you trust it not to, because you own all that code. Likewise you (the author of the outer class) own all the code of a nested class. If you don't want to break encapsulation in the nested class, just avoid writing code that would break encapsulation :)
A nested class is a part of the enclosing class, just like a method is. Exposing private properties through them does not break encapsulation any more than exposing private properties through methods does.
The model that C# uses for access control is that you can access anything you want within the class you're defining, and it's hard to see how it could work any other way.
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