views:

360

answers:

6

Hi,

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?

Thanks.

+1  A: 

Create a ctor in B that allows one to pass in an object of type A, then copy the A fields and set the B fields as appropriate.

Michael Todd
+2  A: 

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.

Reed Copsey
A: 

You could make a Convert method on class B that takes in the base class.

public ClassB Convert(ClassA a)
{
   ClassB b = new ClassB();
   // Set the properties
   return b;
}

You could also have a constructor for ClassB take in an object of ClassA.

Brandon
+1  A: 

I would add a copy constructor to A, and then add a new constructor to B that takes an instance of A and passes it to the base's copy constructor.

Bryan
A: 

No, you can't do that. One way to achieve this is to add a constructor on class B that accepts a parameter of type B, and add data manually.

So you could have something like this:

public class B
{
  public B(A a)
  {
    this.Foo = a.foo;
    this.Bar = a.bar;
    // add some B-specific data here
  }
}
Razzie
I disagree that you should have a Clone() method on A that returns a B, as this introduces a circular dependency.
Matt Howells
I agree with the constructor for class B, but why do you need the CloneToB() method?
Jon Cage
ehm yeah you're right, I shouldn't have included that method. I included it because the poster mentioned MemberWiseClone(). Anyway, this code is not good and I will delete it. Thanks.
Razzie