Unable to create an array in C #

I am trying to make a dynamic array in C #, but I get an annoying error message. Here is my code:

private void Form1_Load(object sender, EventArgs e) { int[] dataArray; Random random = new Random(); for (int i = 0; i < random.Next(1, 10); i++) { dataArray[i] = random.Next(1, 1000); } } 

And the error:

 Use of unassigned local variable 'dataArray' 

It just puzzles my mind. I came from VB, so please, I'm gentle, lol.

Greetings.

+6
arrays c # random
source share
5 answers

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 .

+25
source share

You must initialize the array. If you want something dynamic, you need to use a List object.

+1
source share

It looks like you need to initialize the dataArray.

Make int[] dataArray = new int[10] instead of the code that you have in the first line of the method.

where 10 is the number of items you will be dealing with.

If you are not sure about the size, you are better off using an ArrayList or better yet, List.

+1
source share
  int[] dataArray= new int[10]; Random random = new Random(); for (int i = 0; i < random.Next(1, 10); i++) { dataArray[i] = random.Next(1, 1000); } 
0
source share

Try the following:

  Random random = new Random(); int cnt = random.Next(1, 10); int[] dataArray = new int[cnt]; for (int i = 0; i < cnt; i++) { dataArray[i] = random.Next(1, 1000); } 
0
source share

All Articles