Wednesday, March 11, 2009

No BackStage Pass for Nested Classes in C#

In java land, I used to use nested classes to simplify a class that was getting complicated. If a class grew a cluster of fields and logic related to a single concept, I would create an inner class to encapsulate all that thus making the outer class simpler to understand--basic OO modularity/cohesion principles. Yes, some folks don't like inner classes and in java the compiler actually opens up the access modifiers of the fields--but I found it useful. But in C#, the nested class doesn't share any special access into the outer/enclosing class (perhaps for security reasons?). The workaround seems to be to pass in an instance of the outer class. The problem with this is that without special access to the internals of the outer class (fields, etc), you have to start modifying the access modifiers of the outer class, or start pushing all the state into the nested class via constructors or methods/properties. But that defeats the purpose--the idea was to keep the API to the outer class the same and keep the change encapsulated between the outer and nested class. The workaround I'm using is to have a special method on the outer class that has all the business logic needed to construct the nested class. Not perfect, but it seems like a decent compromise.


hahahaa said...

I have exactly the same problem! I used to program in Java; I want to try out C#. I also use this neat feature of inner classes: creating a private constructor in the inner class, and the outer class can only instanciate it... Worked perfectly and keeps the class design very clean!

I think it's a shame, but as you mentioned, probably there are security reasons for it. My solution is to make the complete inner classes public (since protected fields can't be accessed from it's outer class!), and indeed use the outerclass to populate the inner class.

Anonymous said...

What exactly is your problem?

Anonymous said...

Get your spy crap off my phone.