System.Array.Clone Method

Creates a shallow copy of the Array.

Syntax

public object Clone ()

Returns

A shallow copy of the Array.

Remarks

A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.

In contrast, a deep copy of an Array copies the elements and everything directly or indirectly referenced by the elements.

The clone is of the same Type as the original Array.

This method is an O(n) operation, where n is Array.Length.

Example

This example demonstrates the Array.Clone method.

C# Example

using System;
public class ArrayCloneExample {
  public static void Main() {
    int[] intAryOrig = { 3, 4, 5 };
    //must explicitly convert clones object into an array
    int[] intAryClone = (int[]) intAryOrig.Clone();
    Console.Write( "The elements of the first  array are: " );
    foreach( int i in intAryOrig )
      Console.Write( "{0,3}", i );
    Console.WriteLine();
    Console.Write( "The elements of the cloned array are: " );
    foreach( int i in intAryClone )
      Console.Write( "{0,3}", i );
    Console.WriteLine();
    //Clear the values of the original array.
    Array.Clear( intAryOrig, 0, 3 );
    Console.WriteLine( "After clearing the first array," );
    Console.Write( "The elements of the first  array are: " );
    foreach( int i in intAryOrig )
      Console.Write( "{0,3}", i );
    Console.WriteLine();
    Console.Write( "The elements of the cloned array are: " );
    foreach( int i in intAryClone )
      Console.Write( "{0,3}", i );
  }
}
   

The output is

The elements of the first array are: 3 4 5
The elements of the cloned array are: 3 4 5
After clearing the first array,
The elements of the first array are: 0 0 0
The elements of the cloned array are: 3 4 5

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0