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:
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're working out the size beforehand, you can use an array after all:
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 be aware that arrays are considered somewhat harmful.
You have to initialize the array. If you are wanting something dynamic you need to use a List object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With