I’m trying to make a dynamic array in C# but I get an annoying error message. Here’s 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'
This is just baffling my mind. I came from VB, so please me gentle, lol.
Cheers.
You haven’t created the array – you’ve declared the variable, but not given it a value.
Note that arrays always have a fixed size. If you want a data structure that you can just keep adding to, you should use
List<T>. However, I’d advise working out the size once rather than on each iteration through the loop. For example:Of course if you’re working out the size beforehand, you can use an array after all:
… but be aware that arrays are considered somewhat harmful.