2

If my understanding of deep and shallow copying is correct my question is an impossible one. If you have an array (a[10]) and perform a shallow copy (b[20]) wouldn't this be impossible as the data in b wouldn't be contiguous?

If i've got this completely wrong could someone advise a fast way to immitate (in c#) c++'s ability to do a realloc in order to resize an array.

NOTE
Im looking at the .Clone() and .Copy() members of the System.Array object.

T.C.
  • 123,516
  • 14
  • 264
  • 384
Adam Naylor
  • 5,745
  • 9
  • 46
  • 65

1 Answers1

4

You can't resize an existing array, however, you can use:

Array.Resize(ref arr, newSize);

This allocates a new array, copies the data from the old array into the new array, and updates the arr variable (which is passed by-ref in this case). Is that what you mean?

However, any other references still pointing at the old array will not be updated. A better option might be to work with List<T> - then you don't need to resize it manually, and you don't have the issue of out-of-date references. You just Add/Remove etc. Generally, you don't tend to use arrays directly very often. They have their uses, but they aren't the default case.


Re your comments;

  • boxing: List<T> doesn't box. That is one of the points about generics; under the hood, List<T> is a wrapper around T[], so a List<int> has an int[] - no boxing. The older ArrayList is a wrapper around object[], so that does box; of course, boxing isn't as bad as you might assume anyway.
  • workings of Array.Resize; if I recall, it finds the size of T, then uses Buffer.BlockCopy to blit the contents the actual details are hidden by an internal call - but essentially after allocating a new array it is a blit (memcpy) of the data between the two arrays, so it should be pretty quick; note that for reference-types this only copies the reference, not the object on the heap. However, if you are resizing regularly, List<T> would usually be a lot simpler (and quicker unless you basically re-implement what List<T> does re spare capacity to minimise the number of resizes).
Marc Gravell
  • 927,783
  • 236
  • 2,422
  • 2,784
  • Some valid points, but i am specifically looking at arrays. I don't want the overhead incurred from objects that box arrays such as lists. Do you have any details on the inner workings of the Array.Resize method? ie is it very fast? – Adam Naylor Jan 11 '09 at 10:17