System.ICloneable.Clone Method

Creates a new object that is a copy of the current instance.

Syntax

public object Clone ()

Returns

A new object that is a copy of this instance.

Remarks

The resulting clone must be of the same type as, or compatible with, the original instance.

An implementation of ICloneable.Clone can perform either a deep copy or a shallow copy. In a deep copy, all objects are duplicated; in a shallow copy, only the top-level objects are duplicated and the lower levels contain references. Because callers of ICloneable.Clone cannot depend on the method performing a predictable cloning operation, we recommend that ICloneable not be implemented in public APIs.

See object.MemberwiseClone for more information on cloning, deep versus shallow copies, and examples.

Example

The following example shows an implementation of ICloneable.Clone that uses the object.MemberwiseClone method to create a copy of the current instance.

C# Example

using System;
class MyClass :ICloneable {
    public int myField;
    public MyClass() {
        myField = 0;
    }
    public MyClass(int value) {
        myField = value;
    }
    public object Clone() {
        return this.MemberwiseClone();
    }
}
public class TestMyClass {
    public static void Main() {
        MyClass my1 = new MyClass(44);
        MyClass my2 = (MyClass) my1.Clone();
        Console.WriteLine("my1 {0} my2 {1}",my1.myField, my2.myField);
        my2.myField = 22;
        Console.WriteLine("my1 {0} my2 {1}",my1.myField, my2.myField);
    }
}

The output is

my1 44 my2 44
my1 44 my2 22

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0