1

I have two objects such as A : B

I want to copy all values from A to B at run time

Code

Cow cow = db.Cows.Find(id);

CowDetailViewModel model = new CowDetailViewModel(); //  CowDetailViewModel : Cow

I want to copy value from cow variable to model. there are additional properties in CowDetailViewModel which i would change after copying values.

tereško
  • 58,060
  • 25
  • 98
  • 150
Shanker Paudel
  • 740
  • 1
  • 9
  • 21
  • you have to copy every property inside 'cow' to 'model' `model.X = cow.X; model.Y = cow.Y;` and so on. – AthibaN Sep 25 '13 at 12:35
  • 1
    First rule of asking for help: did you search it yourself first? [here](http://stackoverflow.com/questions/1198886/c-sharp-using-reflection-to-copy-base-class-properties), and [here](http://stackoverflow.com/questions/729527/is-it-possible-to-assign-a-base-class-object-to-a-derived-class-reference-with-a) or [here](http://stackoverflow.com/questions/9010123/creating-a-cloned-copy-of-subclass-from-baseclass). If working for it is not your thing (see comment above), use reflection. – bkdc Sep 25 '13 at 12:38
  • I know about copying each property.. but i was looking for a more need way... i have 10 properties to copy. – Shanker Paudel Sep 25 '13 at 13:35

2 Answers2

1
CowDetailViewModel model = new CowDetailViewModel()
{
     model.Property1 = cow.Property1,
     model.Property2 = cow.Property2
     ////
     ////
};
Neel
  • 11,625
  • 3
  • 43
  • 61
  • 1
    or define a constructor that takes the base class instance as a parameter and simply write `CowDetailViewModel model = new CowDetailViewModel(cow);` – bkdc Sep 25 '13 at 12:42
0

You could create a simple extension method to copy all public properties

public static class CopyHelper
{
    public static void CopyFrom(this object target, object source)
    {
        foreach (var pS in source.GetType().GetProperties())
        {
            foreach (var pT in target.GetType().GetProperties())
            {
                if (pT.Name != pS.Name) continue;
                (pT.GetSetMethod()).Invoke(target, new[] {pS.GetGetMethod().Invoke(source, null)});
            }
        }
    }
}