Welcome :Guest

Congratulations!!!

Top 5 Contributors of the Month
Melody Anderson

 Home >> Code Snippets >> Collections >> Post New Resource

Make Clone of Array Element

Posted By:Ravi Ranjan Kumar       Posted Date: June 30, 2011    Points: 40    Category: Collections    URL: http://www.dotnetspark.com

This Code Snippet enable you to make Clone of array.

Clone means creating shallow copy of array.

suppose we create an array x and we want to make same copy of array to Y then in that case we can use Clone of array.
Take a look how
``` int[] arr1 = new int[5];
arr1.SetValue(5, 0);
arr1.SetValue(10, 1);
arr1.SetValue(15, 2);
arr1.SetValue(20, 3);
arr1.SetValue(25, 4);```
here making an array of integer data type with maximum capacity of 5. and putting value in arr1 by using SetValue function. SetValue is used to insert element at specified position in array

and now see how array arr1 is cloning to arr2
`int[] arr2 = (int[])arr1.Clone(); // Creating Clone array arr2 of arr1`
after clone you can change the value of array arr2 it will never effect arr1 data.

Whole Program :-
``` class Program
{
public static void DisplayArray(Array arr)
{
for (int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0); i++)
{
Console.WriteLine(arr.GetValue(i));
}
}
static void Main(string[] args)
{
int[] arr1 = new int[5];
arr1.SetValue(5, 0);
arr1.SetValue(10, 1);
arr1.SetValue(15, 2);
arr1.SetValue(20, 3);
arr1.SetValue(25, 4);

Console.WriteLine("Value in arr1 is :");
DisplayArray(arr1);
Console.WriteLine("Value of Clone of arr1 is :");

int[] arr2 = (int[])arr1.Clone();    // Creating Clone array arr2 of arr1

arr2.SetValue(100, 0);  // we can change the value at specified position of previous array

DisplayArray(arr2);