This can be done using Reflection. But won't it be an overkill? Reflection can do a lot more; it can clone objects in type-agnostic manner, through type metadata discovery, when you have no preexisting knowledge of the type, but you are talking about one fixed type. Besides, reflection is relatively slow.
So, are you sure that you don't want just to code cloning manually? No? Then drill down in this direction:
First, get a
runtime type:
http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx[
^].
You got the instance of
System.Type
. Now, get the properties:
http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx[
^].
With each property, you can access property values through its
getter and
setter. You will need a type instance, a reference for which you can get or set a property value:
http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.canread.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.canwrite.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getmethod.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.setmethod.aspx[
^].
The last two links shown above explain how to obtain getter and setter. It has the type
MethodInfo
:
http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.aspx[
^].
Finally, you use a getter or a setter to get or set the property variable, through using the invocation method:
http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx[
^],
http://msdn.microsoft.com/en-us/library/4k9x6bc0.aspx[
^].
Basically, that's it. You have source object, its reference, create a new object, obtain its reference. Read all properties in one, set in another one, using the two references, which are passed as the parameter named
obj
in one of two invocation methods referenced above.
[EDIT]
I just described the most universal approach, fully type-agnostic. You can also consider type-specific approach. Please see my comment below; let's assume shallow cloning, by the reasons I explained. (However, we can consider deep cloning, which I actually tried out; it is not available in .NET as something actually existing.)
You need to derive all types you want to clone, and, if they not implement
System.IClonable
, implement it. Please see:
http://msdn.microsoft.com/en-us/library/system.icloneable.aspx[
^].
Perhaps this is what you already know, then I'm just confirming its applicability.
—SA