Resizing arrays in C#

G

Guest

H

I'm a former VB programmer and I have a issue with Arrays in C

If I can't tell the size in advance how can I solve the issue since C# does not suppor
resizing arrays like VB do (i.e. Redim Preserve MyArray(x)

Kjell
 
W

William Stacey [MVP]

Use an ArrayList.

using System.Collections;

ArrayList al = new ArrayList();
al.Add("one");
al.Add("two");
al.RemoveAt(1); // remove "two"
al.Add("three");
foreach(string s in al)
{
Console.WriteLine(s);
}

If you then need a regular array, use the ToArray() method.
 
J

John Baro

You can use an arraylist or if you want a typed array you can use the copyto
method of the array.
array1 (10 long)
array 2 (11 long)
copy array1 into array two and you have a resized array
HTH
JB
 
T

TheNedMan

Kjellwrote:
Hi
I'm a former VB programmer and I have a issue with Arrays in C#

If I can't tell the size in advance how can I solve the issue since C# does not support
resizing arrays like VB do (i.e. Redim Preserve MyArray(x))

Kjell

As John said, an ArrayList may be more useful to you, but if you want
to change array sizes on the fly then here's an example from Instant
C#, the vb.net to C# converter:

VB Code:
Dim x() As Integer
ReDim Preserve x(3)

C# Code:
//INSTANT C# NOTE: The following 4 lines reproduce what 'ReDim
Preserve' does behind the scenes in VB.NET:
//ORIGINAL LINE: ReDim Preserve x(3)
int[] x = null;
int[] Temp1 = new int[4];
if (x != null)
System.Array.Copy(x, Temp1, x.Length);
x = Temp1;
 
C

Cat

William Stacey said:
Use an ArrayList.

using System.Collections;

ArrayList al = new ArrayList();
al.Add("one");
al.Add("two");
al.RemoveAt(1); // remove "two"
al.Add("three");
foreach(string s in al)
{
Console.WriteLine(s);
}

If you then need a regular array, use the ToArray() method.
Sorry to interrupt but was just wondering.. how do you specify the type of
array you want returned? Say, you want a string[] returned..
 
J

Jon Skeet [C# MVP]

Sorry to interrupt but was just wondering.. how do you specify the type of
array you want returned? Say, you want a string[] returned..

Use myArrayList.ToArray(typeof(string))
 
N

Niki Estner

The same way VB does it: create a new array with different size, and copy
all the data (that is exactly what Redim does).
You can also have this transparently done hidden away from you using an
ArrayList.

Niki
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top