Saturday, March 19, 2011

Copying Array's Content to Another

Several methods used to copy the contents of an array to another.

Random r = new Random();
int[] pins = new int[4]{ r.Next() % 10, r.Next() % 10,
                         r.Next() % 10, r.Next() % 10 };

// 1st method
int[] copy = new int[pins.Length];
for (int i = 0; i < pins.Length; i++ )
{
 copy[i] = pins[i];
}

// 2nd method
int[] copy2 = new int[pins.Length];
pins.CopyTo(copy2, 0); //starting from index 0 of copy2

// 3rd method
int[] copy3 = new int[pins.Length];
Array.Copy(pins,copy3,copy3.Length);

// 4th method
int[] copy4 = new int[pins.Length];
copy4 = (int[])pins.Clone();

All of them are copying the reference of the original array, not the value.

No comments:

Post a Comment