ICloneable Interface

System/ICloneable

ICloneable

System

Indicates whether the object implements a method that creates a copy of itself.

This interface is supported by some types that need to provide a cloning mechanism. Implement this interface to indicate that your object can be cloned.

Members

  • Clone()
    Creates a new object that is a copy of the current instance.
    Returns:
    A new object that is a copy of this instance.

Remarks

The Clone() method typically performs a shallow copy. If you need a deep copy, you will need to implement custom cloning logic.

The ICloneable interface is generally discouraged in new development. It's often better to provide explicit copy methods (e.g., Copy(), CloneTo()) or use constructor-based copying for better clarity and control.

Example Usage


using System;

public class MyClass : ICloneable
{
    public int Value { get; set; }
    public string Name { get; set; }

    public MyClass(int value, string name)
    {
        Value = value;
        Name = name;
    }

    public object Clone()
    {
        // This is a shallow copy
        return new MyClass(this.Value, this.Name);
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        MyClass original = new MyClass(10, "Example");
        MyClass copied = (MyClass)original.Clone();

        Console.WriteLine($"Original: Value={original.Value}, Name={original.Name}");
        Console.WriteLine($"Copied: Value={copied.Value}, Name={copied.Name}");

        // Demonstrate that it's a shallow copy (for mutable objects, changes to original
        // would affect copy if 'Name' was mutable and shared reference)
        original.Value = 20;
        Console.WriteLine($"\nAfter changing original.Value:");
        Console.WriteLine($"Original: Value={original.Value}, Name={original.Name}");
        Console.WriteLine($"Copied: Value={copied.Value}, Name={copied.Name}");
    }
}
                    

Related Topics