Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't make an array in C#

Tags:

arrays

c#

random

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.

like image 312
Josh Avatar asked Mar 22 '10 20:03

Josh


2 Answers

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.

like image 72
Jon Skeet Avatar answered Sep 21 '22 20:09

Jon Skeet


You have to initialize the array. If you are wanting something dynamic you need to use a List object.

like image 34
Bryan Denny Avatar answered Sep 20 '22 20:09

Bryan Denny