user160677
user160677

Reputation: 4303

C# - Array Copying using CopyTo( )-Help

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.

Upvotes: 4

Views: 14694

Answers (4)

Reed Copsey
Reed Copsey

Reputation: 564383

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();

Upvotes: 9

Ruben
Ruben

Reputation: 15515

In this particular case, just use

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500135

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 :)

Upvotes: 9

MusiGenesis
MusiGenesis

Reputation: 75296

Try this instead:

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

Upvotes: 4

Related Questions