Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner classes in C#

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?

like image 391
Justin Avatar asked Nov 28 '22 23:11

Justin


2 Answers

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)

like image 135
Ian Ringrose Avatar answered Dec 13 '22 09:12

Ian Ringrose


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

like image 26
leppie Avatar answered Dec 13 '22 08:12

leppie