Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested class written outside of the class

I like using private nested classes, except that they always feel so cluttered. Normally I put them in their own #region, but I would prefer them to be separate from their parent class in terms of location, and I also don't really want them in separate files. What I decided to do was to make their parent class partial, and then to place the child class physically below the parent class in the file.

Unfortunately it seems that you can't have more than one partial class definition per file either.

(EDIT: it turns out you can have more than one partial part per file; it's just the forms designer that doesn't like it.)

What I would really like to do is something like (all in one file):

internal class Parent
{
}

private class Parent.Child1
{
}

private class Parent.Child2
{
}

but it seems like all I can do is either generate a new source file for every new child class, or arrange them like this:

internal class Parent
{
   private class Child1
   {
   }

   private class Child2
   {
   }
}

Is there any way to accomplish what I'm trying to do here?

like image 938
Dave Cousineau Avatar asked Jun 06 '13 23:06

Dave Cousineau


1 Answers

The closest you can get to this type of encapsulation is using a partial parent class:

internal partial class Parent
{
    private Child1 c1Instance = new Child1();
    private Child2 c2Instance = new Child2();
}

internal partial class Parent
{
    private class Child1
    {
    }
}

internal partial class Parent
{
    private class Child2
    {
    }
}

You can split these up into multiple files, the end result will be the same - Child1 and Child2 will be private classes internal to Parent and inaccessible elsewhere.

Makes it a bit more confusing sometimes, but I think it's the closest thing to what you are trying to achieve.

Clarification

A C# source file can hold any number of namespaces, and each namespace can contain any number of structs and classes.

This is a valid (but not very functional) C# source file:

using System;

namespace FirstNS
{
    public class Class1
    {
    }

    public class Class2
    {
    }

    public partial class Parent1
    {
    }

    public partial class Parent1
    {
        private class Child1
        {
        }

        private class Child2
        {
        }
    }
}

namespace FirstNS.ChildNS
{
    public class Class3
    {
    }
}

Compiling that gives you the following classes:

FirstNS.Class1
FirstNS.Class2
FirstNS.Parent1
FirstNS.Parent1.Child1 (private)
FirstNS.Parent1.Child2 (private)
FirstNS.ChildNS.Class3

You could also split each of the class definitions above into multiple files, if you have a reason to do so.

like image 59
Corey Avatar answered Oct 02 '22 16:10

Corey