Clone Wars: Object copy using reflection

Ever needed to copy the properties of one object to another where the objects did not inherit from an Interface or Abstract class? In defense of the pragmatic programmer, this situation should never happen. However, I have run into this situation twice when dealing with web services from an external Java source. You first must call a Session service to get a “ticket” back that must be included at the top of each subsequent web service request. The session object is just an xml serialized object that must be deserialized into a SessionObject. The problem is that when Visual Studio creates the proxy against the WSDL for the other services, they each encapsulate their own version of SessionObject. Even though they have the same schema, they are not the same object to .NET. This particular web service suite requires this type of object sharing a lot, so I created a helper function that would simplify the object copy using reflection. The thing I like is that you could theoretically fill a simple object based on a more complex object that contained more properties.
private object CopyObject(object objSource, object objTarget)
{
  Type typeSource = objSource.GetType();

  foreach (PropertyInfo propTarget in objTarget.GetType().GetProperties())
  {
     PropertyInfo propSource = typeSource.GetProperty(propTarget.Name);
     object valueSource = propSource.GetValue(objSource, null);

     if (propSource.PropertyType.Equals(propTarget.PropertyType))
     {
        propTarget.SetValue(objTarget, valueSource, null);
     }
     else if (valueSource == null)
     {
        propTarget.SetValue(objTarget, null, null);
     }
     else
     {
        object newTarget = Activator.CreateInstance(propTarget.PropertyType);
        newTarget = CopyObject(valueSource, newTarget);
        propTarget.SetValue(objTarget, newTarget, null);
     }
  }

  return objTarget;
}

Advertisements

About Jeremy Mullinax-Hill

I am a lead/senior developer with more than 10 years experience in both the public and internal applications for Fortune 500s and mid-sized View all posts by Jeremy Mullinax-Hill

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: