Search code examples
c#objectcopysubclass

How to "clone" an object into a subclass object?


I have a class A and a class B that inherits class A and extends it with some more fields.

Having an object a of type A, how can I create an object b of type B that contains all data that object a contained?

I have tried a.MemberwiseClone() but that only gives me another type A object. And I cannot cast A into B since the inheritance relationship only allows the opposite cast.

What is the right way to do this?


Solution

  • There is no means of doing this automatically built into the language...

    One option is to add a constructor to class B that takes a class A as an argument.

    Then you could do:

    B newB = new B(myA);
    

    The constructor can just copy the relevant data across as needed, in that case.