C # - Copying an array using CopyTo () -Help

I need to copy the following int array to an array:

int[] intArray=new int[] {10,34,67,11};

      

I tried like

Array copyArray=Array.CreateInstance(typeof(int),intArray.Length,intArray);
intArray.CopyTo(copyArray,0);

      

But it seems I made a mistake, so I didn't get the result.

+2


source to share


4 answers


It works:

int[] intArray = new int[] { 10, 34, 67, 11 };
Array copyArray = Array.CreateInstance(typeof(int), intArray.Length);
intArray.CopyTo(copyArray, 0);
foreach (var i in copyArray)
    Console.WriteLine(i);

      

You had one extra "intArray" in your Array.CreateInstance.

That being said, it can be simplified if you don't need the Array.CreateInstance method (not sure what what you are trying to work out):



int[] intArray = new int[] { 10, 34, 67, 11 };
int[] copyArray = new int[intArray.Length];
intArray.CopyTo(copyArray, 0);

      

Even easier:

int[] intArray = new int[] { 10, 34, 67, 11 };
int[] copyArray = (int[])intArray.Clone();

      

+5


source


Do you know what is int[]

already there Array

? If you just need to pass it to something receiving Array

and you don't mind if it changes the content, just go to the original link.

Another option is to clone it:



int[] clone = (int[]) intArray.Clone();

      

If you really need to use Array.CopyTo

then use the other answers, but otherwise this route will be easier :)

+7


source


Try this instead:

int[] copyArray = new int[intArray.Length];
Array.Copy(intArray, copyArray, intArray.Length);

      

+4


source


In this particular case, just use

int[] copyArray = (int[]) intArray.Clone();

      

+1


source







All Articles