Strongly-Typed Cloning

Problem
You’re going to implement the ICloneable interface. What methods should you have?

Solution
Implement two Clone methods: 1. A public, strongly-typed method that returns an instance of the current type. 2. A private method that implements the interface and returns a generic object.

Example

public class Account : ICloneable {
    // The public Clone method returns an Account object.
    public Account Clone() {
        return (Account) (this as ICloneable).Clone();
    }

    // The private Clone method returns a generic object.
    object ICloneable.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