c# – Are public nested classes a bad practice?


Here I look at some classes of standard libraries and think why they were not made nested and public in order to emphasize their "area".

For example, there is DataTable and DataRow . DataRow does not seem to be used anywhere outside the DataTable context, and moreover, there is no constructor => creation is possible only through a factory method. Or DataColumn

So why not emphasize ownership by moving the classes inside the DataTable ?

And in general, it seems, I didn’t see very often (in my opinion, never) that they would use this opportunity.

Why is that?


Well, why, it is used, but only for those types that do not particularly appear directly in the code. For example, List<T>.Enumerator , which is used only implicitly by compiler-generated code for foreach. It is really not recommended to use them for ordinary types, there is even a special warning of CA1034 analyzers for this. The reason is banal – it's inconvenient; each time such a type is used outside, you must attribute the name of the containing type; you cannot shorten it using using. Well, from an architectural point of view: nesting is not just a scope, it allows a nested class to work with private members of the containing one. If it is not necessary by the logic of the interaction of these classes, it is better not to mess with such an encapsulation violation.

Scroll to Top