Deep Copying an Object in VB.NET

clive All, ASP.Net, Development, Tech Tip, VB.Net

A curious omission in .NET is the ability to make a deep copy of an object which is independent of the original object – i.e. you can change the copy without changing the original. If you simply copy an object in .NET with assignment, all you are doing is pointing a second variable at the same object in memory, and if you change an element of one object, you will change the other too.

If you want to do this, use this example of the definition of a user object type ‘todo1’ as a guideline:

Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary

<Serializable()> _
Public Class todo1
Implements ICloneable

Public placementid As Integer = 0
Public candidateid As Integer = 0
Public candidatename As String = ""
Public clientid As Integer = 0
Public clientname As String = ""
Public placementstartdate As Date = Nothing
Public placementenddate As Date = Nothing
Public readyforbilling As Boolean = False
Public fullday As Integer = 0
Public halfday As Integer = 0
Public chargerate As Decimal = 0.0
Public payrate As Decimal = 0.0
Public dateworked As Date = Nothing
Public candidatephone As String = ""
Public clientphone As String = ""
Public status As String = ""
Public key As String = ""

Public Function Clone() As Object Implements System.ICloneable.Clone
Dim m As New MemoryStream()
Dim f As New BinaryFormatter()
f.Serialize(m, Me)
m.Seek(0, SeekOrigin.Begin)
Return f.Deserialize(m)
End Function

End Class

The parts in italics are the bits you need to add to make the object cloneable.

In your code, you can then do this:

Dim t1 as todo1 = New todo1
Dim t2 as todo1 = t1.Clone

The 2 objects, t1 and t2 are now independent of each other.