A way of casting a base type to a derived type

Not soundly, in “managed” languages. This is downcasting, and there is no sane down way to handle it, for exactly the reason you described (subclasses provide more than base classes – where does this “more” come from?). If you really want a similar behaviour for a particular hierarchy, you could use constructors for derived types that will take the base type as a prototype.

One could build something with reflection that handled the simple cases (more specific types that have no addition state). In general, just redesign to avoid the problem.

Edit: Woops, can’t write conversion operators between base/derived types. An oddity of Microsoft trying to “protect you” against yourself. Ah well, at least they’re no where near as bad as Sun.

Leave a Comment