Here is a simple function that will use reflection to deep copy and object, regardless of type. I culled this, in part from a much more complex copy routine I used in the old Web Services days to copy between Nearly Identical(tm) data types. It might not work exactly, bit it gives you the general idea. It is very simplistic and when using raw reflection there are many boundary cases...
public static object ObjCopy(object inObj)
{
if( inObj == null ) return null;
System.Type type = inObj.GetType();
if(type.IsValueType)
{
return inObj;
}
else if(type.IsClass)
{
object outObj = Activator.CreateInstance(type);
System.Type fieldType;
foreach(FieldInfo fi in type.GetFields())
{
fieldType = fi.GetType();
if(fieldType.IsValueType) //Value types get copied
{
fi.SetValue(outObj, fi.GetValue(inObj));
}
else if(fieldType.IsClass) //Classes go deeper
{
//Recursion
fi.SetValue(outObj, ObjCopy(fi.GetValue(inObj)));
}
}
return outObj;
}
else
{
return null;
}
}
Personally, I would use the Serializer routines, since they automatically handle all the boundary cases. By default, at least in .NET 2.0, the system dynamically creates the Serialization assembly. You can speed up Serialization by caching the Serializers. This sample code from my app is caching the XmlSerializers.
protected static XmlSerializer SerializerGet(System.Type type)
{
XmlSerializer output = null;
lock(typeof(SerializeAssist))
{
if(serializerList.ContainsKey(type))
{
output = serializerList[type];
}
else
{
if(type == typeof(object) || type == typeof(object[]) || type == typeof(ArrayList))
{
output = new XmlSerializer(type, objArrayTypes);
}
else
{
output = new XmlSerializer(type);
}
serializerList.Add(type, output);
}
}
return output;
}