Dynamic array in C#

Take a look at Generic Lists.


Expanding on Chris and Migol`s answer with a code sample.

Using an array

Student[] array = new Student[2];
array[0] = new Student("bob");
array[1] = new Student("joe");

Using a generic list. Under the hood the List<T> class uses an array for storage but does so in a fashion that allows it to grow effeciently.

List<Student> list = new List<Student>();
list.Add(new Student("bob"));
list.Add(new Student("joe"));
Student joe = list[1];

Sometimes plain arrays are preferred to Generic Lists, since they are more convenient (Better performance for costly computation -Numerical Algebra Applications for example, or for exchanging Data with Statistics software like R or Matlab)

In this case you may use the ToArray() method after initiating your List dynamically

List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");

string[] array = list.ToArray();

Of course, this has sense only if the size of the array is never known nor fixed ex-ante. if you already know the size of your array at some point of the program it is better to initiate it as a fixed length array. (If you retrieve data from a ResultSet for example, you could count its size and initiate an array of that size, dynamically)

Tags:

C#