Two private subclasses to one public class

130 Views Asked by At

I got a C# project where I need to have a base class and two sub classes and I want the sub classes to be private to the base classes. This is how it looks like:

public class MyBaseClass
{
    public void doMyWork()
    {
        doSubClass1();
        doSubClass2();
    }
}

private class MySubClass1
{
    public void doSubClass1()
    {
        //Do stuff
    }
}

private class MySubClass2
{
    public void doSubClass2()
    {
        //Do stuff
    }
}

How i can i get this to work?

2

There are 2 best solutions below

1
On BEST ANSWER

Does it hurt if the classes themselves are not-so-private but still wrapped in your base & unaccessible outside?

public class MyBaseClass
{
    private readonly MySubClass1 _sub1 = new MySubClass1();
    private readonly MySubClass2 _sub2 = new MySubClass2();

    public void DoMyWork()
    {
        _sub1.DoSubClass1();
        _sub2.DoSubClass2();
    }
}

public class MySubClass1
{
    public void DoSubClass1() { /* Do stuff */ }
}

public class MySubClass2
{
    public void DoSubClass2() { /* Do stuff */ }
}

If this is not good enough and you need those in separate files, as you stated, then you can use partial classes, like so.

Class1.cs file

public partial class MyBaseClass
{
    public void DoMyWork()
    {
        (new MySubClass1()).DoSubClass1();
        (new MySubClass2()).DoSubClass2();
    }
}

Class2.cs file

public partial class MyBaseClass
{
    private class MySubClass1
    {
        public void DoSubClass1() { /* Do stuff */ }
    }
}

Class3.cs file

public partial class MyBaseClass
{
    private class MySubClass2
    {
        public void DoSubClass2() { /* Do stuff */ }
    }
}   

But still it's not quite clear what you are trying to achieve here.

2
On

If you put your subclasses inside of the base class, the base class can access them. To use your example, it would be like this:

public class MyBaseClass
{
    public void doMyWork()
    {
        new MySubClass1().doSubClass1();
        new MySubClass2().doSubClass2();
    }

    private class MySubClass1
    {
        public void doSubClass1()
        {
            //Do stuff
        }
    }

    private class MySubClass2
    {
        public void doSubClass2()
        {
            //Do stuff
        }
    }

}

Note that all I did was move the last } to the bottom.