Search code examples
c#.netprivatenested-classinternal

class modifier issues in C# with "private" classes


I had a class that had lots of methods:

public class MyClass {
    public bool checkConditions() {
        return checkCondition1() &&
               checkCondition2() &&
               checkCondition3();
    }

...conditions methods

    public void DoProcess() {
        FirstPartOfProcess();
        SecondPartOfProcess();
        ThirdPartOfProcess();
    }

...process methods
}

I identified two "vital" work areas, and decided to extract those methods to classes of its own:

public class MyClass {
    private readonly MyClassConditions _conditions = new ...;
    private readonly MyClassProcessExecution = new ...;

    public bool checkConditions() {
        return _conditions.checkConditions();
    }

    public void DoProcess() {
        _process.DoProcess();
    }
}

In Java, I'd define MyClassConditions and MyClassProcessExecution as package protected, but I can't do that in C#.


How would you go about doing this in C#?

Setting both classes as inner classes of MyClass?

I have 2 options: I either define them inside MyClass, having everything in the same file, which looks confusing and ugly, or I can define MyClass as a partial class, having one file for MyClass, other for MyClassConditions and other for MyClassProcessExecution.

Defining them as internal?

I don't really like that much of the internal modifier, as I don't find these classes add any value at all for the rest of my program/assembly, and I'd like to hide them if possible. It's not like they're gonna be useful/reusable in any other part of the program.

Keep them as public?

I can't see why, but I've let this option here.

Any other?

Name it!

Thanks


Solution

  • Your best bet is probably to use partial classes and put the three clumps of code in separate files adding to the same class. You can then make the conditional and process code private so that only the class itself can access them.