Question

Until very recently I hadnt twigged that there was a difference between a normal class, and an inner class / sub class.

What is the relationship between an instance of an inner class and an instance of its containing class, and what is the purpose of inner classes / what makes them different?

Was it helpful?

Solution

Unlike Java, C# - contained classes are nested. There is no relation between containing class instance and instance of contained class. Contained classes are just used in C# to control accessibility of the contained class and avoid polluting namespaces.

(Some companies have a coding standard that each class must go into it’s own file, contained classes is a way round that for small classes.)

In Java an instance (object) of an inner class has a pointer back to the outer class. This was done in Java, as it uses lots of small classes to handle event etc. C# has delegates for that.

(Contained classes were one of the experimental ideals in Java that everyone liked but did not truly prove the test of time. As C# come along a lot later, it could learn from Java what did not work well)

OTHER TIPS

.NET does not have inner classes like Java does. It does have nested classes.

The reason why you would use them, is to control the accessibility of the class.

In C# there are at least 3 differences between regular classes and inner classes which can also form a relationship between an inner class and the outer class that contains it.

  • Inner classes can be declared as protected, internal, protected internal, or private while normal classes cannot.
  • An inner class can access the static members of the containing outer class without using that classe's name.
  • When the inner class accesses an instance of the outer class, it can access that object's private members even if they are not static.

C# - contained classes are nested. There is no relation between containg class instance and instance of contained class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top