Create a Cloneable Object


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


Implement the ICloneable interface, and use the MemberwiseClone method.


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

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.