Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 728
Amrit Avatar asked Jul 01 '11 07:07

Amrit


People also ask

Can nested classes access private members?

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.

Can nested classes access private members C#?

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.

What is the use of nested class in C#?

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.

What are nested classes in VB net?

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.


2 Answers

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

like image 146
Jon Skeet Avatar answered Oct 03 '22 14:10

Jon Skeet


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.

like image 38
Brennan Vincent Avatar answered Oct 03 '22 14:10

Brennan Vincent