Clone a Serializable Object

Problem

You want to create an exact copy of a serializable object. This is useful if the object doesn’t expose a dedicate Clone method.

Solution

Serialize the object to a memory stream, and then deserialize the memory stream.

Discussion

Serialization provides a quick and convenient way to clone an object, provided it’s serializable. You can use any formatter to perform this magic, but BinaryFormatter makes the most sense (because it requires the least amount of memory). You use the MemoryStream class as an intermediary.

The following example clones the serializable Person object from recipe Create a Serializable Object. In order to use it as written, you’ll need to import the System.Runtime.Serialization.Formatters.Binary ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.