Friday, May 26, 2006

Deep Clone function for .Net 2.0

This is an update to some code I originally found in CodeBox for .Net. The purpose of the function is to fully clone a given object. The object passed does need to be serialisable. If it is not the function returns Null.


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

Public Shared Function DeepClone(Of T )(ByVal source As T) As T
If Not source.GetType().IsSerializable Then
Return Nothing
End If

Dim target As T = Nothing
Using ms As New MemoryStream()
Dim bf As New BinaryFormatter()
bf.Serialize(ms, source)
ms.Position = 0
target = bf.Deserialize(ms)
End Using
Return target
End Function

No comments: