.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal

Home >> Code Snippets >> Serilization >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

How to Copy Properties from one object to another object using Reflection

Posted By:Jean Paul       Posted Date: September 27, 2010    Points: 10    Category: Serilization    URL: http://www.dotnetspark.com  

In some cases we have to copy the properties of one object to another - meaning to say - the properties with same name using .Net Reflection.

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




Person p1 = new Person ();

p1.Name = "Person Name";

Person p2 = new Person();

CopyProperties(p1, p2);


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend