Josh
Josh

Reputation: 287

Can't make an array in C#

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.

Upvotes: 6

Views: 945

Answers (5)

Vivek
Vivek

Reputation: 1

Try This:

        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);
        } 

Upvotes: 0

Mikeyg36
Mikeyg36

Reputation: 2828

Looks like you need to initialize the dataArray.

Do int[] dataArray = new int[10] instead of just the code you have there at the first line of the method.

where 10 is the amount of elements you'll be dealing with.

If you're not sure of the size, you'd be better off using an ArrayList or better yet, a List.

Upvotes: 1

Ashish Gupta
Ashish Gupta

Reputation: 15139

    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);
    }

Upvotes: 0

Bryan Denny
Bryan Denny

Reputation: 27596

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500065

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.

Upvotes: 25

Related Questions