Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I deal with this NullReferenceException?

Tags:

arrays

c#

public partial class Form1 : Form
{
    string[] id;

private void button_Click(object sender, EventArgs e)
{
    char[] delimiters = { ',', '\r', '\n' };
    string[] content = File.ReadAllText(CSV_File).Split(delimiters);

    int x = content.GetUpperBounds(0)
    int z = 0;
    int i - 0;

    for (i = 0; i <= x / 3; i++)
        {
            z = (i * 3);
            id[i] = content[z]; // this line gives the error
        }

}
}

I want to get every 3rd value from array content, and put it into array id. This gives a 'NullReferenceException was unhandled' error and suggests I use 'new', but it is not a type or namespace. What should I do here?

They are both string arrays, and the error occurs on the first run so I do not think it is related to exceeding the bounds.


1 Answers

You need to initialize id array before the for loop:

id = new string[x/3];
like image 171
Sergey Kalinichenko Avatar answered Mar 18 '26 00:03

Sergey Kalinichenko