Implementing the ICloneable Interface

Problem
You need to clone a type. What should you do?

Solution
Implement the ICloneable interface for types that may need cloning.

Comments
If possible, make the Clone method public. Include documentation that calls out whether the Clone method performs a shallow or deep copy. You can simplify the Clone method by calling MemberwiseClone when returning a shallow copy of the object.

Example

public class Account : ICloneable {
    // Return a shallow copy of this Account object.
    public object Clone() {
        return this.MemberwiseClone();
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s