I'd like to create a new object of type B from an existing object of type A. B inherits from A. I'd like to ensure that all the property values in the object of type A are copied to the object of type B. What's the best method for achieving this?
class A
{
public int Foo{get; set;}
public int Bar{get; set;}
}
class B : A
{
public int Hello{get; set;}
}
class MyApp{
public A getA(){
return new A(){ Foo = 1, Bar = 3 };
}
public B getB(){
A myA = getA();
B myB = myA as B; //invalid, but this would be a very easy way to copy over the property values!
myB.Hello = 5;
return myB;
}
public B getBAlternative(){
A myA = getA();
B myB = new B();
//copy over myA's property values to myB
//is there a better way of doing the below, as it could get very tiresome for large numbers of properties
myB.Foo = myA.Foo;
myB.Bar = myA.Bar;
myB.Hello = 5;
return myB;
}
}