tags:

views:

47

answers:

2

I'm trying to go the opposite way of what you would normally do.

I have two POCO classes A and B where B inherrits from A

public class A
{
   public int Foo { get; set; }
}

public class B : A
{
   public int Bar { get; set; }
}

B is ment as an extention to A with additional information.

I start by having an instance of class A

A a = new A { Foo = 1 };

And then I wish to extend the information in class A with the additional information and get the final class B. I could map every property from class A to the property in class B, but it does not make much sence to me:

A a = new A { Foo = 1 };
B b = new B { Foo = a.Foo, Bar = 2 };

Or in constructor

A a = new A { Foo = 1 };
B b = new B(a) { Bar = 2 }; // Mapping of value Foo is done in constructor of object B

The result is in eather case a manual mapping of values from object A to B. There must be a smarter way to do this... any suggestions?

A: 

I would regard the "smart" way as being your last suggestion - write a copy constructor for B that knows how to instantiate itself from an A.

Christian Hayter
IMHO that could lead to a maintainaince nightmare. The example is extremely simplified. For my current implementation I do use the last suggestion.
Tim
A: 

If you are actually changing type (rather than casting) - then if you have only a few classes, then just write conversion code - perhaps a ctor for B that accepts a template A. If you have a lot of classes... there are tricks you can do with either dynamic code or serialization. PropertyCopy in MiscUtil will do this, for example (using a dynamic Expression to do the work very quickly):

A a = new A { Foo = 1 };
B b = PropertyCopy<B>.CopyFrom(a);
b.Bar = 2;
Marc Gravell
Marc, I like your suggestion to use reflection. The thought did cross my mind but I did not want to code a property copy method. Thanks for the link to MiscUtil. It saved me valuable time.
Tim