I'm looking for a way to create a generic base class that has a typesafe taxonomy using internal properties. Just to be clear, the class doesn't have to use the generics language feature as long as it is generic itself and I'm looking for something that has compile-time type safety.
As an example here is a simple taxonomy I want to represent using multiple instances of the same class
Wood
Crate
Box
Metal
Crate
Bar
The permutations of which are
Wood Crate
Wood Box
Metal Crate
Metal Bar
initially I though I could use enums to represent the different levels of taxonomy like so
public enum EFirstLevel
{
Wood,
Metal
}
public enum ESecondLevel
{
Crate,
Box,
Bar
}
public class BaseItem
{
EFirstLevel FirstLevel;
ESecondLevel SecondLevel;
public BaseItem(EFirstLevel aFirst, ESecondLevel aSecond)
{
FirstLevel = aFirst;
SecondLevel = aSecond;
}
}
I could create the items above using:
var item1 = new BaseItem(EFirstLevel.Wood,ESecondLevel.Crate)
var item2 = new BaseItem(EFirstLevel.Wood,ESecondLevel.Box)
var item3 = new BaseItem(EFirstLevel.Metal,ESecondLevel.Crate)
var item4 = new BaseItem(EFirstLevel.Metal,ESecondLevel.Bar)
but I could also create
var item5 = new BaseItem(EFirstLevel.Wood,ESecondLevel.Bar)
which for my purposes is incorrect.
Do any of you know of a pattern that would let me create a single class to represent the example taxonomy in a type-safe way that prohibits the creation of incorrect combinations.
It also needs to be applicable to N levels of taxonomy, the 2 levels above are just an example.
Thank you
Update: I do require compile-time type safety. I could do this with multiple classes quite easily using inheritance and such, I'm trying to find a solution using instances of just a single base class.
let me know if you need any more info
Update: @Maarten Yes, i'm trying to sure that the hierarchy is maintained so if EFirstLevel is 1 then ESecondLevel must be either Crate or Box.
Just to clairify i'm happy to have other supporting classes, what i'm trying to avoid is having to explicitly create a class for each taxanomic value.
What I'm trying to accomplish is providing an example layout of class that that maintains this taxanomic type safety so I can reflect over it and permute combinations. While maintaining the type safety should I need to generically instantiate said permutations.
The class upon which I might reflect could come form a third party and as such I might not know beforehand the values for each level. I could generate all the possible combinations into a set of classes with type safe internal enums but this would require regeneration of said classes any time you changed the items in any level. I was just wondering if there was a was to achieve my goals without having to generate any classes.
EDIT: Moved this section to an answer