Return part of array

I am trying to find the fastest way to return a part of an array in C# My current way is as follows:

// .. set int moveCount ..
// .. set int[] childArray ..
int[] realArray = new int[moveCount];
Array.Copy(childArray, realArray, moveCount);
return realArray;

This is the way I see it everywhere on the net, but I wonder if the array will be copied twice now. Once because I do it, and once because of returning.

  • Is this a right assumption?.
  • Is there a better way? I know about Buffer.BlockCopy.
Jon Skeet
people
quotationmark

No, when you return you'll be returning a reference to the array you've just created. The reference will be copied, but that's dirt cheap.

All arrays are reference types, even if the element type of the array is a value type (so int[] is a reference type even though int is a value type).

Now you could still consider returning ArraySegment<int> instead of int[] - that way you wouldn't end up copying any values within the array. On the other hand, if the original array is changed, those changes will affect what the caller sees (and likewise the caller can change the array contents).

people

See more on this question at Stackoverflow