- Home /
The question is answered, right answer was accepted
C# Store different subclasses in one array
Hello,
I wanted to create some easily extendable code. I have a class called Level, which contains some basic things, then I have a class called Building which has Level after : (extends probably) and extends Level functionality. And I have a controller, which stores all levels as Level[].
I wanted to ask, if it is possible to store different subclasses in levels array of Level type and access variables and functions of extended class?
Answer by JoshuaMcKenzie · Feb 07, 2016 at 03:36 PM
you can thanks to Polymorphism, but your controller won't specifically know that one of the levels is actually a building. you would have to manually cast for that special case. However, if you need specific variables from very specific and different subclasses of Level, then your controller is taking on too many responsibilities to be considered "extensible". if its trying to manage too many classes by keeping track of their variables, then its tightly coupled with those classes. (your looking for decoupled classes when looking for extensible code)
what do you expect the controller to use that array of levels for? if theres a common functionality that the controller only cares about you could abstract this functionality from the Building and Level classes into an interface.