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

Create a Cloneable Object

Problem

You want to create a straightforward way for developers to create copies of an object you create.

Solution

Implement the ICloneable interface, and use the MemberwiseClone method.

Discussion

Many .NET objects provide a Clone method that allows the contents of an object to be duplicated in a new object. The correct way to use this pattern with your own objects is by implementing the ICloneable interface.

The ICloneable interface defines a single Clone method. This method can make use of a protected method that all classes inherit from the base System.Object type: MemberwiseClone. This method performs a shallow copy of all the data in the object. Here’s a simple implementation with the Person class introduced in recipe ...

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