Search code examples
c#typesstrong-typingbase-class

How do you work with a variable that can be of multiple types?


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?


Solution

  • I am assuming that the types in your question are sealed. In which case I would just use object parent and use as on the way out. (Using as can 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.)

    Video video = null;
    if ((video = parent as Video) != null) {
      // know we have a (non-null) Video object here, yay!
    } else if (...) {
      // maybe there is the Audio here
    }
    

    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# :-)