0

So I have a parent entity Producer and its child ProducerNS.

ProducerNS inherited all the properties of Producer and an additional field, lets call that anyColumn

I have an object Producer and I want to copy over the object into ProducerNS like so,

Producer producer = getproducer();
ProducerNS producerns = producer;
producerns.anyColumn = 'hellobunnies';

However, I know the above syntax is incorrect. Can I transfer over all the properties without doing so individually? (Producer has a lot of fields) If so, how?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Oct8
  • 77
  • 1
  • 8

2 Answers2

0

You want to do a deep copy of your producer object into your producerns object.

Have a look here for ideas for doing a deep copy in c#, keep in mind that your subclass obviously has your additional property which you will need to take into consideration: How do you do a deep copy of an object in .NET (C# specifically)?

here is a post specifically for subclass copying: How to "clone" an object into a subclass object?

Another option would be to use reflection to get a list of properties from your producer object and use the values of each property in your producerns object. This could be done in a simple foreach loop

Community
  • 1
  • 1
BenM
  • 4,218
  • 2
  • 31
  • 58
0

The best way to achieve what you want without manually implementing copy constructor is to have your getproducer() function to become generic:

T getproducer<T>()
   where T : Producer, new()
{
    var result = new T();
    ...
    return result;
}

...

ProducerNS producerns = getproducer<ProduceNS>();
producerns.anyColumn = 'hellobunnies';
Riad Baghbanli
  • 3,105
  • 1
  • 12
  • 20