Hi folks my question is how can I determine the size of an array in runtime dynamically. Like in VB we do this :-

Dim x() as Integer,i as Integer

i=5
Redim Preserve x(i)

so what is the equivalent syntax for this in C#?

Recommended Answers

All 3 Replies

int i = 5;
int[] x = new int[x];

Another approach is to use Generics.
List<int> x = new List<int>();

x.Add(0); x.Add(1); ..... as many as you want, as often as you want.
When/If you ever need to use it as an array, you can always do this:

int[] z = x.ToArray();


The advantage here is that you can use the List for anything you can do with an array, only you have the added benefit of removing items, and adding items at will without dealing with redimensioning issues like copying the data from the old array into the newly sized array.

IMHO, Lists are far superior to the old style array.

// Jerry

Sorry I mean

int i = 5;
int[] x = new int[i];
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.