Copying an instance of a class object

I recently had a need to copy the instance of a fairly complex class object. More specifically what wanted was to load and instance of the object, from a data source. The object had about 40 properties some of which where collections of other classes.

So creating a new instance of the object then setting each property would be more time consuming and less elegant that I would like. Doing as standard set would just set a reference to the first object. So changes on the second object would made on the first instance. This was not the behavior I wanted either.

After doing a Google search and combining a few examples this what I cam up with.

PublicSub CopyObject( _
ByVal pObjectType As Type, _
ByVal pOriginalObject As Object, _
ByRef pNewObject As Object)

Dim ArPoperties() As Reflection.PropertyInfo = _
pObjectType.GetProperties(Reflection.BindingFlags.Public Or _
Reflection.BindingFlags.Instance)
Dim ObjPropItem As Reflection.PropertyInfo
For Each ObjPropItem In ArPoperties
If ObjPropItem.CanWrite Then
ObjPropItem.SetValue(pNewObject, _
ObjPropItem.GetValue(pOriginalObject, Nothing), Nothing)
End If
Next
End
Sub
As is the goal if this blog. I hope you find this useful.

0 comments: