Connecting Tech Pros Worldwide Forums | Help | Site Map

Clone any object in vb 6.0

Cathode Follower's Avatar
Newbie
 
Join Date: Feb 2008
Posts: 5
#1   Mar 6 '08
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
  13.  
You have to change your class declarations to be serializable to use this code:
Expand|Select|Wrap|Line Numbers
  1. <Serializable()> Friend Class ChargeUnitType
  2.  
The call to clone any object looks similar to this:
Expand|Select|Wrap|Line Numbers
  1. Dim objClonedType As ChargeUnitType = CloneObject(ChargeUnitType) 
  2.  
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
  4.  

Last edited by debasisdas; Mar 7 '08 at 06:54 AM. Reason: added code=vb tags



Cathode Follower's Avatar
Newbie
 
Join Date: Feb 2008
Posts: 5
#2   Mar 13 '08

re: Clone any object in vb 6.0


Sorry I got the title wrong. The example and description refers to .NET ! Woops.
Reply