Can you create private classes in C#?

Archeg picture Archeg · Aug 26, 2010 · Viewed 23.6k times · Source

This is a question for the .NET philosophers:

It is my understanding that Microsoft consciously denied use of private classes in C#. Why did they do this and what are their arguments for doing so?

I, for example, am building a large application that includes a reporting tool. This tool uses a lot of business objects that are used only within the reporting tool and not in other parts of the project. I want to encapsulate them for use only within the reporting tool itself.

Great decision is creating separate project in VS for this tool, and I'll do like that, but I'm interesting, what if I can't do this - for exmple our architecture wasn`t good enough, and we have big single project.

Behind "private class" I mean a class that can't be used in any other namespace, except its own.

My question was not - how can I simulate this, or do in another way. I'm just wondering, why not use private keyword with class keyword without any parent classes. I`m thinking there should be some reason, and I want to know it

Answer

Alex Humphrey picture Alex Humphrey · Aug 26, 2010

Allowing classes to be private to a namespace would achieve no meaningful level of protection.

Any assembly in the world could simply reference your dll, and start writing code in your namespace which accesses your supposedly private classes.

I think that's possibly the answer you'd get from Microsoft.