Amrit
Amrit

Reputation: 903

Access to parent's private properties through nested types in C#

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.

Upvotes: 5

Views: 1744

Answers (3)

Kieren Johnstone
Kieren Johnstone

Reputation: 42003

(IMO) The nested type is a part of the enclosing type, and so it should have access to the private members - just like any other part of that type.

Just like if you make any other part of a type public, that too could expose private properties of the type.

Since only the person who wrote the enclosing type could write the nested type, there's no real risk?

Upvotes: 2

Brennan Vincent
Brennan Vincent

Reputation: 10665

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.

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500555

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 :)

Upvotes: 6

Related Questions