Is it possible to have a private class?

I always wonder if it is possible to have a private class? And what's the point of having such a class?

Thanks for the help.

+7
c #
source share
4 answers

Yes, it is possible to have a private class, but only as an inner class of another class:

public class Outer { private class Inner {} } 

This is usually useful if you want to encapsulate some logic inside the class (external), but to implement it you need a more structured / OO code. I used this template in the past when I needed a container class to process some information in a class method, but the container class does not make sense outside of this logic. Creating a container class of a private inner class means that its use is localized in the outer class that uses it.

It is worth noting that with this structure, the inner class has access to the private members of the outer class, but not vice versa.

+19
source share

The presence of private non-nested classes (visible only for their namespace and child namespaces) will allow you to clear code boundaries when programming in the same assembly.

Having, for example, only an interface and a factory visible from other namespaces in the same assembly, while still having the entire implementation of the interfaces and utility classes (which no one has business knowledge from the namespace).

You can still do this with a large partial class that replaces the namespace and nested classes inside, but a very bad hack and unit testing becomes almost impossible.

+3
source share

Yes you can - usually these are nested classes inside another type. This means that you can combine logic into a nested class without exposing the class to anything else. Internal is also useful for nested classes.

Note that there are some arguments against design requiring nested classes - I tend to use them when they seem appropriate.

+2
source share

You may have a private class inside another class.

You can use a private class to encapsulate logic and implementation. For example, you can declare an iterator implementation in your ICollection implementation.

+2
source share

All Articles