PM's Blog

Pramod Mohanan's notes about ASP.NET, MVC, C#, SQL, jQuery, Bootstrap

Loop through properties of an object

I just had a need to loop through all the properties of an object and copy the values of the properties to another object of the same type. I just discovered that we can use System.Relection to get this done.

For example two objects sourceObject and destinationObject are objects of class Person.

using System.Reflection;
namespace ExampleOfUsingRefelction
{
  public class Person
  {
    public int Id {get; set;}
    public string Name {get; set;}
  }

  public class Example
  {
    Person sourceObject = new Person();
    sourceObject.Id = 10;
    sourceObject.Name = "Pramod";

    person destinationObject = new Person();
    //now we use Reflection to assign all property values of the sourceObject to the properties of desObject
    PropertyInfo[] properties = destinationObject.GetType().GetProperties();
    foreach(PropertyInfo pi in properties)
    {
       object value = sourceObject.Gettype().GetProperty(pi.Name).GetValue(sourceObject, null);
       pi.SetValue(destinationObject, value, null);
    }
    // at this point we have assigned values of all properties of source
    // object to the destination object without accessing it by its name
  }
}
Updated: December 11, 2011 — 6:24 pm

Leave a Reply

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

PM's Blog © 2015