In general, given a class A, and a derived class DerivedFromA, and an instance of A, is there a way to construct DerivedFromA from that instance?
E.g., let’s say that DerivedFromA simply overrides one or more methods or properties of A. Let’s say I have some Container class with a CreateA() method that returns an instance of A, and I either can’t or don’t want to override or otherwise mess with that Container class. What I want to do is take the instance returned by Container.CreateA(), pass it to a DerivedFromA( A instanceOfA) constructor and have the resulting object be treated just like instanceOfA and use all of instanceOfA’s methods, properties, and data except for the ones I have overridden.
BTW, the language in question is C#, it that makes a difference.
Thanks.
You’ll have to make a new
DerivedFromAinstance, and use that instance instead of your original. If you do that, however, it will work fine.Just add a constructor like you showed:
Then, when you call, you can just do: