Reflection–Copy Properties

Often in enterprise standard projects, we will be dealing with converting one entity into another.  Most of the cases the properties will be of same name and type.  In this case the following method is useful. 

The method saves the time of assigning each properties line by line.  Reflection is implemented to achieve this.

Reflection is upto 8 times slower than normal code but for a few dozen of entities the slowness does not arise.

 

  public static void CopyProperties(object source, object dest)
        {
System.Type type1 = source.GetType();
            System.Type type2 = dest.GetType();

            foreach (PropertyInfo pInfo1 in type1.GetProperties())
                foreach (PropertyInfo pInfo2 in type2.GetProperties())
                    if (pInfo1.Name == pInfo2.Name)
                    {
                        if (pInfo1.CanRead && pInfo2.CanWrite)
                            pInfo2.SetValue(dest, pInfo1.GetValue(source, null), null);
                        break;
                    }
        }

Usage:

public class Person
{
    public int Id
    {
        get;
        set;   
    }

    public string Name
    {
        get;
        set;   
    }
}

// Code

Person p1 = new Person ();

p1.Name = “Person Name”;

Person p2 = new Person();

CopyProperties(p1, p2);

Leave a Reply

Your email address will not be published. Required fields are marked *