Namespace: System

ICloneable Interface

public interface ICloneable

Description

Supports cloning. Cloning creates a new instance of a class that is a copy of the current instance.

Requirements

Interface Description
System.Object The base class for all types in the .NET Framework.

Members

Name Description
Clone() Creates a new object that is a copy of the current instance.

Methods

public object Clone()

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

Return Value

A new object that is a copy of this instance.

Remarks

The ICloneable interface defines a single method, Clone, which is used to create a copy of an object. The copy can be a shallow copy or a deep copy, depending on the implementation of the Clone method.

A shallow copy creates a new object, but it copies the references to the objects contained in the original object. If the contained objects are modified, those modifications will affect both the original and the copied object.

A deep copy creates a new object and recursively copies all objects contained in the original object. This ensures that modifications to the copied object do not affect the original object.

While ICloneable is supported by many .NET Framework types, it is not universally implemented, and its usage is often debated. Consider using copy constructors or factory methods as alternatives for object duplication.

Example

The following example demonstrates how to implement and use the ICloneable interface.

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()
    {
        // Shallow copy implementation
        return new MyClass(Value, Name);
    }

    public override string ToString()
    {
        return string.Format("Value: {0}, Name: {1}", Value, Name);
    }
}

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

        Console.WriteLine("Original: {0}", original);
        Console.WriteLine("Cloned:   {0}", cloned);

        // Modifying the original does not affect the clone in this shallow copy for primitives
        original.Value = 20;
        original.Name = "Modified Original";

        Console.WriteLine("Original after modification: {0}", original);
        Console.WriteLine("Cloned after original modification: {0}", cloned);
    }
}
Back to Top