Enumerate and copy properties of one object to another object of the same type

I use a third-party control that exports some data in different formats. The control has a property ExportSettings. But it is read-only.

I need to manually set its properties, for example

ctrl.ExportSettings.Paging = false;
ctr.ExportSettings.Background = Color.Red;

So, I get the ExportSettings object from the user, and I want to set it to the control.

How to copy all its values ​​to a user control?

+5
source share
5 answers

Try reflection based cloning:

private object CloneObject(object o)
{
    Type t = o.GetType();
    PropertyInfo[] properties = t.GetProperties();

    Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, 
        null, o, null);

    foreach (PropertyInfo pi in properties)
    {
        if (pi.CanWrite)
        {
            pi.SetValue(p, pi.GetValue(o, null), null);
        }
    }

    return p;
}
+18
source
  static void CopyProperties(object dest, object src)
  {
   foreach (PropertyDescriptor item in TypeDescriptor.GetProperties(src))
   {
    item.SetValue(dest, item.GetValue(src));
   } 
  }
+16
source

You can do this through Reflection .

Something like that:

Type exportSettingType = ctrl.ExportSettings.GetType();

foreach (PropertyInfo property in exportSettingType.GetProperties())
{
    object value = property.GetValue(ctrl.ExportSettings, null);
    property.SetValue(secondControl.ExportSettings, value, null);
}
+1
source

All Articles