C# – Are nested classes under-rated

cdesign

I'm not trying to say I know something everyone else doesn't but I've been solving more and more designs with the use of nested classes, so I'm curious to get a feeling for the acceptablilty of using this seemingly rarely used design mechanism.

This leads me to the question: am I going down an inherintly bad path for reasons I'll discover when they come back to bite me, or are nested classes maybe something that are underrated?

Here are two examples I just used them for: https://gist.github.com/3975581 – the first helped me keep tightly releated heirarchical things together, the second let me give access to protected members to workers…

Best Answer

I would not call this a "rarely used design mechanism" - at least, not universally: although there are shops where some contributors may frown upon using nested classes, this is not an obscure feature at all.

Although the existence of classes with assembly visibility and the introduction of lambdas has significantly reduced the need for nested classes*, they remain a valid design choice. Although there is some overlap with internal classes inside a namespace, the nested classes feature is unique in letting you hide a class entirely inside another class.


* The use of a similar feature in Java is much higher, because other alternatives available in C# are not there in Java.

Related Topic