Cook Computing

Nested Classes

August 21, 2002 Written by Charles Cook

I've convinced myself to use nested classes as mentioned in the previous entry here and put up with a large source file. The benefits are reducing pollution of the namespace in which the outer class is defined, restricting the visibility of the nested classes to the class which uses them, and providing access to the private members of the outer class.

The first point allows me to define other classes in the same namespace which will use similarly named but different "helper" classes. I could handle this by giving the helper classes unique names but I think its better to handle this with a proper namespace mechanism rather than some arbitrary naming scheme.

The second point is achieved by making the nested classes private. This restricts visibility of the nested classes to their outer class (and incidentally a nested class is the only case where a class can be marked as private).

Finally, the nested classes need priviledged access to some members of their outer class. I can mark these members are private yet the nested classes will still be able to access them. Note that although a nested class has access to the private members of the outer class, the converse does not apply: the outer class cannot access the private or protected members of the nested class.

To illustrate this with some code:


class Outer
{
  private void X() { }

  private class Nested
  {
    public void A() { }
    private void B() { }
  }
}

Code within class Outer can instantiate class Nested but can only call method A. Code outside class Outer cannot instantiate or access class Nested. Code within class Nested can call method X of class Outer even though this method is private.

The large source file does make coding more difficult and so I'm experimenting for the first time with code regions and the outlining functionality of Visual Studio. But I would much prefer to be using class augmentation.