Friday, April 19, 2024 12:44

Table of contents >> Objects > Nested classes

Nested classes

C# offers nested classes, which just like all the other nested programming concepts, implies a construct (class) defined inside the body of another construct (class). The class defined this way is called “inner class”, while the one which contains it, is called “outer class”.

Inner classes are mainly used for two reasons:

  • to better organize and structure the code, specially when trying to replicate objects of the real world, where some inner objects cannot exist without their enclosing objects, or when certain objects depend on their mutual existence.
  • to hide and anonymize a class inside another class, so that it is only exposed and accessible through the enclosing class.

As a general rule, nested classes are a rarely used programming concept, mainly because they increase the complexity and the structure of the code, and also because they add up to the nested levels.

Nested classes are declared the same way as the normal classes are declared, but they are declared inside the body of another class. They allow 9 access modifiers in their declaration, but only 4 are actually of any importance to you. They are:

  • public – an inner class is accessible from any assembly.
  • internal – an inner class is available in the current assembly, in which is located the outer class.
  • private – access is restricted only to the class holding the inner class.
  • static – an inner class contains only static members.

The other five modifiers that are rarely used are: abstract, protected, protected internal, sealed and unsafe.

Keep in mind that the keyword this has only meaning related to the elements of the inner class. We cannot access elements of the outer class inside the inner class using the keyword this. On the other side, static members of the outer class are accessible to the inner class, regardless of their protection level.

This is an example of outer-inner classes declaration:

The result would be the following:

inner loops

In the example, the outer class OuterClass defines into itself as a member the class InnerClass. Non-static inner class methods have access to their own body this as well as the instance of outside class parent (through syntax this.parent, if the parent reference is added by the developer). In the example, while creating the inner class, parent reference is set to constructor of the outer class.

As already stated, whenever you have alternatives and you don’t have to illustrate the concept of real world sub-object, avoid using nested classes. Still, as an example, if you have a class named Car, it would make sense to have an inner class called Engine, which cannot exist or have any functionality outside the enclosing Car object.

Tags: , , , , ,

Leave a Reply



Follow the white rabbit