Software Engineering
c# project-structure namespace
Updated Mon, 25 Jul 2022 02:58:23 GMT

When no other class ever needs to touch the (nested) class - should I always make it a (private) nested class?


And what is the recommended file structure?

The question is a bit similar to this one, but I'm looking for more explicit recommendations.

In theory I think it's a good concept to keep files short so you don't see other noise of nested classes where you're not interested in the implementation details at that point in time.

I think there are then two options left (but maybe I'm missing something).

Option A using partials and nested classes:

ClassA.cs

namespace Example
{
    public partial ClassA
    {
        [...]
    }
}

ClassA.Helpers.cs

namespace Example
{
    public partial ClassA
    {
        private class ClassB
        {
            [...]
        }
        private class ClassC
        {
            [...]
        }
    }
}

What I don't like here is the extra indention from the class - it makes it a bit harder to read, because your eye is used to scan for i.e. two indentions for class members.

Option B: don't make it a nested class, but make it an internal class within it's own namespace - so it doesn't pollute the main namespace:

ClassA.cs

namespace Example
{
    public class ClassA
    {
    }
}

Helpers/ClassB.cs

namespace Example.Helpers
{
    internal class ClassB
    {
    }
}   

Am I missing a third option? Are there any recommendations, defaults or guidelins




Solution

Bringing namespaces in for this is not right, namespaces are for big scope borders, typically on the module/assembly level. This is about keeping your scope tight, if you introduce a new namespace, that namespace will be visible outside the scope of the class which you do not want.

The partial class would be OK. I personally would just use a region named Classes within the parent class, that would get them out of the way for me without the need for an extra file in the project. If you do use a partial class, name the file MainClass.Classes.cs or something similar so it will be obvious the classes belong to MainClass and the files will be displayed in succession in the solution explorer.







Linked Articles

Local articles referenced by this article: