Assume a generic List of type Packet, holding custom classes extending Packet, such as LoginPacket or ChatPacket.
Let’s say I put these in a list. When I take them out, the most ‘specific’ type each will be is Packet. I want to cast these into their more specific types though, back into their original LoginPacket or ChatPacket or back into whatever their original types were.
Question: How can I do this?
Reference: How to cast an object programmatically at runtime?
So…it seems like if these custom classes share a common interface, it would solve the casting problem? But if so, my classes can’t all share one interface. I need to build interfaces upon interfaces and classes upon classes. So…how would I do this? Sorry if this question isn’t so accurate. Not sure how to articulate my exact issue.
You could have a whole long list of if/else or a switch
However, that can become unwieldly.
You may wish to revisit your class design. By having a
List<Packet>, you’re effectively stating you do not care about the differences between the derived children, at least in terms of their unique APIs.In other words, if your design is
You’re saying you only care about being able to access
Foo().If you do care about differences, perhaps you can express those differences with polymorphism via abstract or virtual methods in the base and overriden behaviors in the children. Therefore you still have a collection of base classes, but you still get the custom behaviors as specified by each child.
Here, you call just call
Foo(). No casting necessary.