Array clone

In this chapter you will learn:

  1. How to clone an array with reference data
  2. How to clone value array

Clone array with reference data

using System;//from   ja  va 2  s.c  o  m

class MyClass
{
   public int Value = 5;
}

class MainClass
{
   static void Main()
   {
      MyClass[] orignalArray = new MyClass[3] { new MyClass(), new MyClass(), new MyClass() }; 
      
      MyClass[] cloneArray = (MyClass[])orignalArray.Clone();                   

      cloneArray[0].Value = 1;                               
      cloneArray[1].Value = 2;
      cloneArray[2].Value = 3;

      foreach (MyClass a in orignalArray)
         Console.WriteLine(a.Value);

      foreach (MyClass a in cloneArray)
         Console.WriteLine(a.Value);
   }
}

The code above generates the following result.

Clone Value Array

using System;//from ja  v  a2  s. com

class MainClass
{
   static void Main()
   {
      int[] orignalArray = { 1, 2, 3 };                    
      int[] cloneArray = (int[])orignalArray.Clone();         

      cloneArray[0] = 10;
      cloneArray[1] = 20;
      cloneArray[2] = 30;

      foreach (int i in orignalArray)
         Console.WriteLine(i);

      foreach (int i in cloneArray)
         Console.WriteLine(i);
   }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Reverse an array using Array.Reverse
  2. Reverse an array in a range
  3. Use the Reverse() method to reverse the elements in string Array
Home » C# Tutorial » Array
Array
Array loop
Array dimension
Jagged Array
Array length
Array Index
Array rank
Array foreach loop
Array ForEach Action
Array lowerbound and upperbound
Array Sort
Array search with IndexOf methods
Array binary search
Array copy
Array clone
Array reverse
Array ConvertAll action
Array Find
Array SequenceEqual