Tuesday, February 9, 2010

Using Reflection in C# - Copying objects across namespaces


.
You may not find yourself in this situation that often, but sometimes you have two objects of the same structure who find themselves in different namespaces and you want to copy one to the other. An example of this is having two webservices who use the same Customer object. If a return of a Customer from one web service is to be used in the other, you face a sticky situation. The second service won't accept the return from the first without some tricks because they are in different namespaces.

This can be solved 3 ways that I'm aware of. Of the 3, I prefer to use reflection. The first is to hack your Reference.cs files to remove the namespacing and make them match. The problem with this is that you have to do this each time you update your reference from the WSDL. Not good in my opinion.

The second way is to implement the iConvertible interface, something I find overkill.

The third way is to copy all of the properties of the first object to an empty copy in the second namespace using reflection. Below is a method called ObjectCopy that will do just that.



//Use System.Reflection at the top of your file

public Object ObjectCopy(Object from, Object to)
{
Type fromType = from.GetType();
Type toType = to.GetType();

PropertyInfo[] fromProps = fromType.GetProperties();
PropertyInfo[] toProps = toType.GetProperties();

for (int i = 0; i < fromProps.Length; i++)
{
PropertyInfo fromProp = fromProps[i];
PropertyInfo toProp = toType.GetProperty(fromProp.Name);
if (toProp != null)
{
toProp.SetValue(to, fromProp.GetValue(from, null), null);
}
}

return (to);
}

No comments:

Post a Comment