Cloning in vb6 was always a pain. It was so easy to get the code wrong, and the problems it caused were endless - normally stack overflow.
In .Net you do not have to do any cloning any more - you can simply serialise the object and then copy it into the target object. The technique is quite widely used and described - but it is interesting to use it with generics, as it means that you can use it anywhere in your application. Here is a code sample showing what to do:
-
Public Function CloneObject(Of T)(ByVal obj As T) As T
-
Try
-
Dim stream As New MemoryStream(1024)
-
Dim formatter As New BinaryFormatter()
-
formatter.Serialize(stream, obj)
-
stream.Seek(0, SeekOrigin.Begin) ' go back to the start
-
CloneObject = DirectCast(formatter.Deserialize(stream), T) 'get new object
-
stream.Close() ' clear down the memory
-
Catch excGeneric As Exception
-
ReportException(excGeneric)
-
End Try
-
End Function
-
You have to change your class declarations to be serializable to use this code:
-
<Serializable()> Friend Class ChargeUnitType
-
The call to clone any object looks similar to this:
-
Dim objClonedType As ChargeUnitType = CloneObject(ChargeUnitType)
-
Occasionally, for reasons I do not understand, the code fails on trying to deserialize, but for these cases, on the advice of Microsoft, I have included the following code in the object being serialized, and the problem has gone away:
-
Friend Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
-
MyBase.New(info, context)
-
End Sub
-