views:

762

answers:

4

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?

+1  A: 

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

adatapost
+4  A: 

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

leppie
+9  A: 

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 the 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 like 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)

Ian Ringrose
+1  A: 

In C# I know of 3 differences between regular classes and inner classes which can also form a relationship relationship between an inner class and the outer class that contains it.

One difference is that 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.

Another difference is 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.

INTPnerd