Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a private class?

Tags:

c#

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

Thanks for helping.

like image 825
Richard77 Avatar asked Jul 13 '10 08:07

Richard77


Video Answer


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 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.

like image 77
adrianbanks Avatar answered Sep 23 '22 15:09

adrianbanks


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.

like image 45
Julien Roncaglia Avatar answered Sep 22 '22 15:09

Julien Roncaglia


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.

like image 38
Adam Houldsworth Avatar answered Sep 23 '22 15:09

Adam Houldsworth


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.

like image 44
onof Avatar answered Sep 23 '22 15:09

onof