Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Array Copying using CopyTo( )-Help

Tags:

c#

I have to copy the following int array in to Array :

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

i tried as

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

But ,it seems i have made a mistake,so i did not get the result.

like image 203
user160677 Avatar asked Nov 29 '22 19:11

user160677


2 Answers

This 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 line.

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

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

Even simpler:

int[] intArray = new int[] { 10, 34, 67, 11 };
int[] copyArray = (int[])intArray.Clone();
like image 80
Reed Copsey Avatar answered Dec 13 '22 04:12

Reed Copsey


Are you aware that an int[] is already an Array? If you just need to pass it to something accepting Array, and you don't mind if it changes the contents, just pass in the original reference.

Another alternative 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 simpler :)

like image 20
Jon Skeet Avatar answered Dec 13 '22 06:12

Jon Skeet