Redimensioning an Array

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I found an article that discussed dynamic allocation of an array but it seems
extremely overloaded in time requirements for function. The process is fine
if there's no data in it, but if there is an additional set of steps is
necessary that make it seem less than efficient:

tmp = Array.CreateInstance(...)
orig.CopyTo(tmp,0)
orig = tmp


I would have thought an Add/Remove method would have been provided and
solution would have been more efficient.

Help? Thoughts?
 
In the VB.NET world, there is the ReDim Preserve operation that lets you
dynamically resize an array while preserving it’s contents. Unfortunately,
here in the C# world, we do not have that option and have to use a method not
unlike what you found, that of creating a new array of the size we want,
copying the values from the old array to the new, and updating the reference
to point to the new array.

This is at least the case if you are using an actual array ([] style).
Another option you have is using the ArrayList class from System.Collections
which does incorporate the Add() and Remove() methods you are looking for,
however it internally pretty much does what was described above.

Brendan
 
Hi Brad ! :O)

When it comes to dynamic arrays, I usually go with the ArrayList class. The
ToArray() method it provides is really handy when you need to convert its
content back to a normal strongly-typed array.
 
Brad,

You can use the ArrayList type in the System.Collections namespace to
create a dynamically allocated array (it's really a wrapper to provide that
kind of functionality, arrays lengths are immutable once created).

In .NET 2.0, you can use the generic List<T> class which will do the
same thing but in a type-safe manner (which is also quicker when using value
types as well, because there is no boxing overhead that you get with the
ArrayList class).

Hope this helps.
 
Brendan Grant said:
In the VB.NET world, there is the ReDim Preserve operation that lets you
dynamically resize an array while preserving it?s contents.

It doesn't really. It creates a new array of a different size and
copies the contents of the original array. That's a very different
operation, because it means any other references to the original array
won't see any change to the size (or any changes to the new array). If
the array object itself changed, the change would be visible through
all references.
 
Back
Top