tags:

views:

2303

answers:

5

I am relatively new to C# and each time I begun to work on a C# project (I only worked on nearly mature projects in C#) - I'm wondering why there is 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 used by ClassM
         <some code>
      }

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

I would be glad to ear you on that subject - Am I right ?

Thanks in advance !

+1  A: 

For me personally I only create private inner classes if I need to create in-process collections of an object that may require methods on them.

Otherwise, it could cause confusion for other developers working on the project to actually find these classes, as they are not very clear as to where they are.

Tom Anderson
But since they are privates classes, other developers should not be aware of them, unless, of course, they have to maintain the outer class. Of course, this can be a problem where people are not aware of private inner classes. Thanks for your answer !
Sylvain
If that confused my developers I would get new developers.
DancesWithBamboo
+6  A: 

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 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.

Jon Skeet
Very clever!But I will never use it. Software book writers and their readers (!) are often clever peoples. They think to a lot of bright things and it's cool. But software maintainers are ordinary people who didn't read Gamma/Skeet.My guest: the more it is clever, the less it is maintenable...
Sylvain
That's true until it becomes a recognised pattern. It's like "while ((line = streamReader.ReadLine()) != null)" looks bad to start with - side-effects in a while condition! But when it's idiomatic, you get past that smell and appreciate the conciseness.
Jon Skeet
(Responses are too short here - sorry) - I must say that I am working on softwares for insurance corporations : maintenability is the mantra. -- But I still have your C# book at hand at work and I'm still reading it. Can wait to have a job in a software company :i)
Sylvain
I have posted something about inner classes implementing the outer class here : http://www.developpezvous.com/2008/06/21/c-comment-creer-un-wrapper-proprement. It is based on .NET's Collection class. Reading again your answer, and finding very clever, I think that there are a lot possibilities there
Sylvain
@Sylvain: I think it's like LINQ - it *adds* to the maintainability when you're used to it, but looks odd at first sight. But I agree that it's not a common pattern in C# yet :(
Jon Skeet
@Jon, (1) What is the advantage of FirstCleverEnum and SecondCleverEnum being embedded classes? (2) Why do these classes contain "enum"? The outer class seems to be an enum, but the inner ones don't. (3) Not that I would want to, but why can't I do `MyCleverEnum.First.First.First.SomeMethod()`? BTW, if you Google "better enum pattern", you get one hit: this SO page :)
DanM
1) They have access to the private constructor of the containing class. You can guarantee they are the *only* classes which will create instances of the outer class - and only the outer class can see them to create instances of them. 2) They're members of the enum, effectively. 3) Because you can't reference static members as if they were instance members (unlike in Java). This is a good thing :)
Jon Skeet
@Jon, thanks! I think I got it now. `MyCleverEnum` acts as both the the holder of the enum members and the interface of each enum member, so it is more succinct than other solutions. The use of embedded classes ensures that the support classes are hidden from outside the class. The private constructor makes the class behave like a static/singleton class from outside the class but like an abstract base class from inside the class.
DanM
A: 

Jon, didn't you also use a nested class in order to create a thread-safe, lazy singleton ?

Frederik Gheysels
+2  A: 

You should limit the responsibilities of each class so that each one stays simple, testable and reusable. Private inner classes go against that. They contribute to the complexity of the outer class, they are not testable and they are not reusable.

Wim Coenen
Simple, testable and reusable are very great. But what about encapsulation? When something should not be seen outside, why make it public? In my book, inner classes can make the whole thing somewhat simpler. And they are testables (with relexion) !
Sylvain
I would pick encapsulation as an argument **against** inner classes. Inner classes can access private members of their outer classes!
Wim Coenen
Your right ! Having an inner class add some sort of coupling between it and the outer class - I did not see it at first - sorry. And thanks !
Sylvain
+1  A: 

The Framework Design Guidelines has the best rules for using nested classes that I have found to date.

Here's a brief summary list

1) Do use nested types when the relationship between type and nested type is such the member-accessibility semantics are desired.

2) Do NOT use public nested types as a logical group construct

3) Avoid using publicly exposed nested types.

4) Do NOT use nested types if the type is likely to be referenced outside of the containing type.

5) Do NOT use nested types if they need to be instantiated by client code.

6) Do NOT define a nested type as a member of an interface.

matt_dev