Private inner classes in C# - why aren't they used more often?

Sylvain Rodrigue picture Sylvain Rodrigue · Jan 17, 2009 · Viewed 67.4k times · Source

I am relatively new to C# and each time I begin to work on a C# project (I only worked on nearly mature projects in C#) I wonder why there are no inner classes?

Maybe I don't understand their goal. To me, inner classes -- at least private inner classes -- look a lot like "inner procedures" in Pascal / Modula-2 / Ada : they allow to break down a main class in smaller parts in order to ease the understanding.

Example : here is what is see most of the time :

public class ClassA
{
   public MethodA()
   {
      <some code>
      myObjectClassB.DoSomething(); // ClassB is only used by ClassA
      <some code>
   }
}

public class ClassB
{
   public DoSomething()
   {
   }
}

Since ClassB will be used (at least for a while) only by ClassA, my guess is that this code would be better expressed as follow :

   public class ClassA
   {
      public MethodA()
      {
         <some code>
         myObjectClassB.DoSomething(); // Class B is only usable by ClassA
         <some code>
      }

      private class ClassB
      {
         public DoSomething()
         {
         }
      }
   }

I would be glad to hear from you on this subject - Am I right?

Answer

Jon Skeet picture Jon Skeet · Jan 18, 2009

Nested classes (probably best to avoid the word "inner" as nested classes in C# are somewhat different to inner classes in Java) can indeed be very useful.

One pattern which hasn't been mentioned is the "better enum" pattern - which can be even more flexible than the one in Java:

public abstract class MyCleverEnum
{
    public static readonly MyCleverEnum First = new FirstCleverEnum();
    public static readonly MyCleverEnum Second = new SecondCleverEnum();

    // Can only be called by this type *and nested types*
    private MyCleverEnum()
    {
    }

    public abstract void SomeMethod();
    public abstract void AnotherMethod();

    private class FirstCleverEnum : MyCleverEnum
    {
        public override void SomeMethod()
        {
             // First-specific behaviour here
        }

        public override void AnotherMethod()
        {
             // First-specific behaviour here
        }
    }

    private class SecondCleverEnum : MyCleverEnum
    {
        public override void SomeMethod()
        {
             // Second-specific behaviour here
        }

        public override void AnotherMethod()
        {
             // Second-specific behaviour here
        }
    }
}

We could do with some language support to do some of this automatically - and there are lots of options I haven't shown here, like not actually using a nested class for all of the values, or using the same nested class for multiple values, but giving them different constructor parameters. But basically, the fact that the nested class can call the private constructor gives a lot of power.