C # - Copying an array using CopyTo () -Help
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 to share
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 to share