1

Possible Duplicate:
What are reasons why one would want to use nested classes?

I found some example code online for something unrelated, and it had nested classes. I thought this was a mistake, and the outer one should have been Namespace, but the code compiled and worked fine.

What are nested classes used for? Is this a good programming practice?

Community
  • 1
  • 1
NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • 1
    And a couple of more duplicates: [When should I create a nested class? Does it make instantiation of the outer class consume more resources?](http://stackoverflow.com/questions/3361830/when-should-i-create-a-nested-class-does-it-make-instantiation-of-the-outer-clas) | [Where and how to use nested classes ?](http://stackoverflow.com/questions/3143670/where-and-how-to-use-nested-classes) | [Why/when should you use nested classes in .net? Or shouldn't you?](http://stackoverflow.com/questions/48872/why-when-should-you-use-nested-classes-in-net-or-shouldnt-you) – Zecc Jun 16 '11 at 09:17
  • Typed my question, scrolled through the list of suggestions... nothing...d'oh – NibblyPig Jun 16 '11 at 09:33

1 Answers1

1
  • So that you don't litter a namespace with classes. Inner, nested classes are visible only to the parent class, or when typing ParentClass.*, rather than spamming the namespace with classes that are only ever used once by one single class
  • It allows you to logically group all elements of a class within a single file (including subclasses)
  • More maintainable. It's easier to read small classes in its parent class rather than having to open another file to read a few lines
foxy
  • 7,599
  • 2
  • 30
  • 34
  • 1
    you can also have multiple (public, private, internal) classes within a single file. – Sebastian Mach Jun 16 '11 at 09:18
  • With regard to readability of smaller classes, quite often using partial classes will resolve that particular problem. – Jamie Dixon Jun 16 '11 at 09:19
  • @Jamie, that's true. But with smaller classes, I find that smaller classes nested in larger ones makes it easier to refer to when revising code. – foxy Jun 16 '11 at 09:25