C# Array - Clone() Method



The C# Array Clone() method creates the shallow copy of the array. This means that it copies both the array structure and the items, but for reference types, it only copies the references, not the objects they point to.

A shallow copy creates a new object that shares the same instance variable as an existing object.

Syntax

Following is the syntax of the C# Array Clone() method −

public object Clone ();

Parameters

This method does not accepts any parameters −

Return value

This method returns an object that is the shallow copy of the array.

Example 1: Cloning a 1D Array of Value Types

Let us crate a basic example of the clone() method. Since integers are value types, changes to the clone do not affect the original. −

using System;
class Program
{
   static void Main()
   {
      int[] original = { 1, 2, 3 };
      int[] clone = (int[])original.Clone();
      clone[0] = 99;
      Console.WriteLine(string.Join(", ", original));
      Console.WriteLine(string.Join(", ", clone));
   }
}

Output

Following is the output −

1, 2, 3
99, 2, 3

Example 2: Cloning a 1D Array of Reference Types

Let us see another example of theclone()method. The array elements are copied as references, but modifying these references in the clone does not affect the original array −

using System;
class Program
{
   static void Main()
   {
       string[] original = { "one", "two", "three" };
       string[] clone = (string[])original.Clone();
       clone[0] = "changed";
       Console.WriteLine(string.Join(", ", original));
       Console.WriteLine(string.Join(", ", clone));
   }
}

Output

Following is the output −

one, two, three
changed, two, three

Example 3: Shallow Copy of Reference Type

This is another example ofthe clone()method. Here, both the original and the clone reference the same Person objects, so changes in one are reflected in the other −

using System;
class Person
{
   public string Name { get; set; }
}
class Program
{
   public static void Main()
   {

      Person[] original = { 
         new Person { Name = "Aman" }, 
         new Person { Name = "Kaushal" }
      };
      Person[] clone = (Person[])original.Clone();
      clone[0].Name = "Rahul";
      Console.WriteLine(original[0].Name);
      Console.WriteLine(clone[0].Name);
   }
}

Output

Following is the output −

Rahul
Rahul
csharp_array_class.htm
Advertisements