C# equivalent of VB Redim

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

Guest

Hi all
Please let me know if there is a C# equivalent method for
the VB Redim statement. Thanks a lot.
 
Please let me know if there is a C# equivalent method for
the VB Redim statement. Thanks a lot.

No - you basically have to create a new array, and then use Array.Copy
or Array.CopyTo to copy the elements from the old one into the new one.
That's what VB.NET's Redim does under the covers anyway, I believe.
 
Hi,

I asked a similar questions about an hour ago :
does something like a realloc() for arrays exist in C# ? (like in C)
or do you have to create a new array-object yourself an then copy the
already existing values in the new array ?

The answer I got was :
The latter. You might want to consider using an ArrayList as a flexible
collection, however.

hth
Chris
----- Original Message -----
From: <[email protected]>
Newsgroups: microsoft.public.dotnet.languages.csharp
Sent: Monday, March 22, 2004 9:30 PM
Subject: C# equivalent of VB Redim
 
From what I remember, Redim changes the size of an array without destroying
its contents when making it larger. If you are in a situation in which the
array may change size, I would recommend using a 'dynamic array' such as
System.Collections.ArrayList. An ArrayList's size is dynamic and it can
return an array with its 'ToArray()' method, like this:

ArrayList al = new ArrayList();
al.Add("Stuff");
string[] strarray = (string[]) al.ToArray(typeof(string));

If you need to use straight arrays, you can set a variable to a new array
size any time, but the previous elements are lost.
string[] strarray = new string[123];

To keep the previous elements, you can create a temporary array with the new
size and copy the elements from the old array to the new array using
Array.Copy or a loop.

Good luck!

- Noah Coad -
Microsoft MVP
 
No. You must use something like this:

public Array ReDim1DArray(Array origArray, int nNewSize)

{

// Determine the types of each element

Type objType = origArray.GetType().GetElementType();

// Construct a new array a different number of elements

// The new array preserves types from the original array

Array newArray = Array.CreateInstance(objType, nNewSize);



// Copy the original array elements to the new array

Array.Copy(origArray, 0, newArray, 0,

Math.Min(origArray.Length, nNewSize));

// Return the new array

return newArray;

}

This method then is called like this (using the 1-D array, myArray, from the previous code listing):

myArray = (string[]) ReDim1DArray(myArray, 3);

myArray[2] = "elem3";



Regards,
LC
 
Back
Top