ICloneable (Interface)
Defines a method that supports cloning, which creates a copy of the current instance. This is a shallow copy clone.
Members
| Name | Description |
|---|---|
| Clone() | Creates a new object that is a copy of the current instance. |
Remarks
The ICloneable interface defines a single method, Clone(), which allows an object to create a copy of itself. The Clone() method returns an object that is a copy of the current instance. This is typically a shallow copy; that is, if the object contains references to other objects, the references are copied, but the objects themselves are not duplicated.
It is recommended that implementations of ICloneable.Clone() use the MemberwiseClone() method to perform a shallow copy. For a deep copy, you must manually implement the cloning of referenced objects.
Example
The following C# code example demonstrates how to implement and use the ICloneable interface.
using System;
public class MyClass : ICloneable
{
public int Id { get; set; }
public string Name { get; set; }
public MyClass(int id, string name)
{
Id = id;
Name = name;
}
// Implement the ICloneable.Clone() method
public object Clone()
{
// Use MemberwiseClone for a shallow copy
return this.MemberwiseClone();
}
public override string ToString()
{
return $"ID: {Id}, Name: {Name}";
}
}
public class Program
{
public static void Main(string[] args)
{
MyClass original = new MyClass(1, "Example");
MyClass cloned = (MyClass)original.Clone();
Console.WriteLine($"Original: {original}");
Console.WriteLine($"Cloned: {cloned}");
// Modify the original and see that the clone is unaffected (for shallow copy)
original.Name = "Modified";
Console.WriteLine($"Original after modification: {original}");
Console.WriteLine($"Cloned after modification: {cloned}");
}
}