By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,286 Members | 2,443 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Clone any object in vb 6.0

Cathode Follower
P: 5
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:

Expand|Select|Wrap|Line Numbers
  1. Public Function CloneObject(Of T)(ByVal obj As T) As T
  2.         Try
  3.             Dim stream As New MemoryStream(1024)
  4.             Dim formatter As New BinaryFormatter()
  5.             formatter.Serialize(stream, obj)
  6.             stream.Seek(0, SeekOrigin.Begin) ' go back to the start
  7.             CloneObject = DirectCast(formatter.Deserialize(stream), T) 'get new object
  8.             stream.Close() ' clear down the memory
  9.         Catch excGeneric As Exception
  10.             ReportException(excGeneric)
  11.         End Try
  12.     End Function
You have to change your class declarations to be serializable to use this code:
Expand|Select|Wrap|Line Numbers
  1. <Serializable()> Friend Class ChargeUnitType
The call to clone any object looks similar to this:
Expand|Select|Wrap|Line Numbers
  1. 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:
Expand|Select|Wrap|Line Numbers
  1.  Friend Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
  2.         MyBase.New(info, context)
  3.     End Sub
Mar 6 '08 #1
Share this Article
Share on Google+
1 Comment

Cathode Follower
P: 5
Sorry I got the title wrong. The example and description refers to .NET ! Woops.
Mar 13 '08 #2