开发者

Is it possible to have a private class?

开发者 https://www.devze.com 2023-01-07 14:28 出处:网络
I always wonder if it is possible to have a priva开发者_开发技巧te class? And, what would be the point of having such class?

I always wonder if it is possible to have a priva开发者_开发技巧te class? And, what would be the point of having such class?

Thanks for helping.


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 when you want to encapsulate some logic inside of a class (the outer one), but need a more structured/OO design of code to implement it. I have used this pattern in the past when I need a container class to process some information within a method of a class, but the container class has no meaning outside of this logic. Making the container class a private inner class means that its use is localised to the outer class that utilises it.

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


Having private non-nested classes (Visible only to their namespace and child namespaces only) would allow to clean code boundaries while 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 all the implementation of the interface and utility classes (that no-one have business knowing out of the namespace) there.

It is still possible to do it somewhat with a big partial class replacing a namespace and nested classes inside but it's a very bad hack and unit testing become nearly impossible.


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

Note however that there are some arguments against a design requiring nested classes - I tend to use them when they seem a good fit though.


You can have a private class, inside another class.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号