Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Posts Tagged ‘.net c# reflection example’

Reflection–Copy Properties

Posted by JP on November 22, 2011

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);

Advertisements

Posted in C#, Reflection | Tagged: | Leave a Comment »