O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required