• 9
• 16
• 15
• 12
• 9

# [.net] How to copy arrays?

This topic is 3408 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

It seems that this one is always giving me troubles. Im trying to copy an array I want a copy not a reference so Im doing aux = myarray.Clone(); but whenever I want to retrieve my aux value it returns the current value for myarray?? I really dont get it any tips for this one?

##### Share on other sites
A copy of an array is not an array of copies. Both arrays (the original and the copy) will contain the same objects, because cloning is shallow. So, clone the contents as well.

##### Share on other sites
In laymens terms, if you want to copy an array you need to make two arrays and allocate memory
for both of them, this is what keeps them seperate. Then you do the copies. There are calls you can make that let you do this in one call, but if you want to explicitly ensure the copy takes place then explicitly do a new array1, new array2 ... for (){ array2[x] = array1[x]} ... might not be the most efficient, but you know it works.

Hope that helps.

##### Share on other sites
oh ok ill go the for() route

... maybe its time to toy with that parallel.for() ive seen somewhere on the net

class Program{    static void Main(string[] args)    {        byte[] a1 = new byte[] { 1, 5, 2, 34, 1, 2, 3 };        byte[] a2 = new byte[a1.Length];        a1.CopyTo(a2, 0);        Array.Copy(a1, a2, a1.Length);        Buffer.BlockCopy(a1, 0, a2, 0, a1.Length);        // etc...    }}