Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

object

copy

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

I've to manually set its properties like

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 can I copy all its member values to the user control?

like image 621
NLV Avatar asked Dec 28 '10 13:12

NLV


3 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;
}
like image 172
nan Avatar answered Oct 07 '22 19:10

nan


  static void CopyProperties(object dest, object src)
  {
   foreach (PropertyDescriptor item in TypeDescriptor.GetProperties(src))
   {
    item.SetValue(dest, item.GetValue(src));
   } 
  }
like image 21
Akash Kava Avatar answered Oct 07 '22 17:10

Akash Kava


Use AutoMapper :

Its very easy to use.

Getting started with AutoMapper

like image 43
decyclone Avatar answered Oct 07 '22 17:10

decyclone