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.
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();
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With