I frequently link objects to their parents using:
Video parent;
Sometimes I have objects that can be children of different object types, so do I:
int parentType;
Video parentVideo; // if parent == VIDEO then this will be used
Audio parentAudio; // if parent == AUDIO then this will be used
Is there a better way?
How do I work with a variable that can be an instance of different types?
Edit: Of course, if Video and Audio inherit from the same baseclass (eg. Media) I could do this:
Media parent;
But what if the parents do not inherit from the same baseclass?
I am assuming that the types in your question are sealed. In which case I would just use
object parentand useason the way out. (Usingascan have a higher performance impact than checking a flag, but… not a concern in anything I have done and it can also be nicely used in a null-guard.)The above is actually just a silly C# way of writing a one-off-pattern-match on an unconstrained discriminated union (object is the union of every other type in C# 🙂