[C#] Copy of Array in C#

When you copy an array in C#, for example, to copy from Array A to Array B, and if you want to use those amounts separately…, don’t write like following difinitely.
Array_B = Array_A;

I believe that it’s common sense for intermediate level, this is just passing Reference type.

Therefore, if you change the amount of Array_B, automatically the amount of Array_A will be changed. (We can also say that it’s changing Array_A itself.)

[Copy for Single-Dimensional Array]
Actually, we need to use ‘CopyTo’ for this case.

Array_A.CopyTo (Array_B, 0);

Parameter: (destination array to be copied, index number to be started)

[Copy for Multidimensional Array]
However, if you use it for multidimensional array, instead of single-dimensional array, following error will happen.

In the case, you can use ‘Array.Copy’.

using.System;
Array.Copy (Array_A, 0, Array_B, 0, 40);

Parameter: (source array to be copied, index number of source array to be started, destination array to be copied, index number of destination array to be started, how many arrays to be copied)
Important: Need to use ‘using.System’.

Even you wrongly use passing Reference type, sometimes it goes successfully by chance, however in that case, later you’ll need to take more time to debag that.
You should avoid that kind of situation.

[Original Japanese Site: http://blog.lab7.biz/archives/2651297.html ]

Leave a Reply

Your email address will not be published. Required fields are marked *