Mono Class Library: System.ICloneable Overview | Members

System.ICloneable.Clone Method

Creates a copy of the current instance. [Edit]

public object Clone ()

Returns

A object of the same type as the current instance, containing copies of the non-static members of the current instance. [Edit]

Remarks

The exact behavior of this method is unspecified. The intent of the method is to provide a mechanism that constructs instances that are copies of the current instance, without regard for class-specific definitions of the term "copy".

Note: Use the object.MemberwiseClone method to create a shallow copy of an object. For more information, see object.MemberwiseClone .

Operation
This method is required to return an instance of the same type as the current instance.

Note to Inheritors
Implement this method to provide class-specific copying behavior.

Usage
Use the ICloneable.Clone method to obtain a copy of the current instance.

[Edit]

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