You did not create an array - you declared a variable, but did not give it a value.
Note that arrays always have a fixed size. If you need a data structure that you can simply add, you should use List<T> . However, I would advise working out the size once, and not at each iteration through the loop. For example:
private void Form1_Load(object sender, EventArgs e) { List<T> dataArray = new List<T>(); Random random = new Random(); int size = random.Next(1, 10); for (int i = 0; i < size; i++) { dataArray.Add(random.Next(1, 1000)); } }
Of course, if you earn the size in advance, you can use an array:
private void Form1_Load(object sender, EventArgs e) { Random random = new Random(); int size = random.Next(1, 10); int[] dataArray = new int[size]; for (int i = 0; i < size; i++) { dataArray[i] = random.Next(1, 1000); } }
... but keep in mind that arrays are considered somewhat harmful .
Jon skeet
source share