What is the best way to create a clone of a DTO? There is not an ICloneable interface or a BinaryFormatter class in Silverlight. Is reflection the only way?
A:
I believe the standard cloning functionality was left out to keep it simple and lightweight. I believe you could use either JSON or XML serialization to achieve the same thing though. Not sure about the performance costs though.
Craig Nicholson
2008-10-19 21:10:15
+2
A:
Here is the code we came up with for cloning. This works in Silverlight 2 & 3.
Public Shared Function Clone(Of T)(ByVal source As T) As T
Dim serializer As New DataContractSerializer(GetType(T))
Using ms As New MemoryStream
serializer.WriteObject(ms, source)
ms.Seek(0, SeekOrigin.Begin)
Return DirectCast(serializer.ReadObject(ms), T)
End Using
End Function
Mike Schall
2010-02-03 22:27:06