ICloneable interface in C#

The ICloneable interface contains one member, Clone, which is intended to support cloning beyond that supplied by MemberwiseClone. It is a procedure that can create a true, distinct copy of an object and all its dependent object, is to rely on the serialization features of the .NET framework.

There are two ways to clone an instance:

An instance is an actual object created to the specification defined by a class.

  1. Shallow copy - may be linked to data shared by both the original and the copy
  2. Deep copy - contains the complete encapsulated data of the original object

Syntex

[ComVisibleAttribute(true)]
public interface ICloneable

Example

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;

public
class value : ICloneable
{
    public int i;
    public int j;
 
    public value(int aa, int bb)
    {
        i = aa;
        j = bb;
    }
 
    public string ToString()
    {
        return "(" + i + "," + j + ")";
    }
 
    public virtual object Cloning()
    {
        return new value(i, j);
    }
    object ICloneable.Clone()
    {
        return Cloning();
    }
}

Output

clone.gif