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.
Nested types in C# have the ability to access the parent’s private properties. Is
Share
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 🙂