102425074
102425074

Reputation: 811

How to copy properties of a base class object to a child class object

Consider below two class:

public class AAA{
   string _Test1;
   public string Test1{
   get=>_Test1;
   set{_Test1=value;}
   }
}

public class BBB:AAA{
  string _Test2;
   public string Test2{
   get=>_Test2;
   set{_Test2=value;}
   }
}

And here are the Objects:

AAA aaa=new AAA(){Test1="123"};
BBB bbb=new BBB(){Test2="456"};

I want to copy all the value of aaa to the child class bbb.

In fact, there are many properties in the base class object and I don't want to copy the values manually, one by one :

bbb.Test1=aaa.Test1;


How can I do it? Would you please help me? Thank you.

Upvotes: 1

Views: 979

Answers (1)

Philip Atz
Philip Atz

Reputation: 938

You can use reflection to do this:

foreach (var field in typeof(AAA).GetFields())
{
    field.SetValue(bbb, field.GetValue(aaa));
}

The idea is to loop through all the fields of type AAA in bbb and assign to them the values that they had in aaa. Note that this will only work for fields; if you want to also copy the values of properties, you can extend this to also use the .GetProperties() method.

Upvotes: 1

Related Questions