Sometimes there are classes you find you use in every project. I remember once (shudder) I, rather inelegantly instantiated a class, and performed a manual copy of all the properties in the object (when the pressure was on, and I just needed to make the thing work).
I have also found myself spending hours chasing subtle and hard to debug issues where ICloneable has been used - which, incidentally, is widely accepted as an interface one ought never use – or Object.MemberwiseClone. It turns out the only way to do this correctly, is to serialise the object, and then use the deserialised object, implemented here using an extension method.
Even though this is quite straightforward, I still am posting this however , because I find I need to use this functionality frequently, and often I no longer have access to the source, or it takes ages to find the class. The Visual Basic code sample is after the C# one.
/// Provides a method for performing deep copying of an object.
/// Binary Serialization is used to perform the copy.
internal static class ObjectCopier
/// Perform a deep copy of an object.
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
internal static T Clone<T>(this T source)
throw new ArgumentException("The type must be serializable.", "source");
// Don’t serialize a null object, simply return the default for that object
if (ReferenceEquals(source, null))
IFormatter formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
”’ Provides a method for performing deep copying of an object.
”’ Binary Serialization is used to perform the copy.
Friend NotInheritable Class ObjectCopier
Private Sub New()
”’ Perform a deep copy of an object.
”’ <typeparam name="T">The type of object being copied.</typeparam>
”’ <param name="source">The object instance to copy.</param>
”’ <returns>The copied object.</returns>
Friend Shared Function Clone(Of T)(source As T) As T
If Not GetType(T).IsSerializable Then
Throw New ArgumentException("The type must be serializable.", "source")
‘ Don’t serialize a null object, simply return the default for that object
If ReferenceEquals(source, Nothing) Then
Dim formatter As IFormatter = New BinaryFormatter()
Using stream = New MemoryStream()
Return DirectCast(formatter.Deserialize(stream), T)