0

I am learning how to do multidimensional arrays and I am getting this reference error while trying to populate the array. Anyone have any ideas?

 public static string[][] itemLines;


    public static void readTxtFile()
    {
        try
        {
            string[] lines = new string[420];

            using (StreamReader sr = new StreamReader(TextFileDirectory.fileDirectoryThree))
            {
                int counter = 0;
                while (!sr.EndOfStream)
                {
                    lines[counter] = sr.ReadLine(); //All lines are in an array index
                    counter++;
                }
            }

            for (var i = 0; i < lines.Length; i++)
            {
                itemLines[i] = lines[i].Split('Ü'); //All lines are in multiplexed array
                Console.WriteLine("Line " + i + "'s first value is: " + itemLines[i][0]);         
            }

            }
        }      
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }
    }

This is kicking my butt. I can't seem to figure this out.

Edit: I found the answer out. I had to have a counter variable and declare the arrays correctly with it.

2 Answers2

1

An array is an object. All objects need to be initialized. The object you created at the start public static string[][] itemLines has never been initialized. You have created a two dimensional array, which is an array of arrays. itemLines[i] = .. accesses the i element of the array itemLines object (which is again an array of arrays). In other words, what you are doing is equal to this:

int[] i;
i[0] = 8;

The above will not work because i was never initialized.

Sample initialization:

string[][] myArr = new string[9][];
string[][] myArr2 = new string[9][8];
Neville Nazerane
  • 5,682
  • 3
  • 31
  • 68
-1

First you need to initialize array

itemLines=new string[10][];

then this error will go out

and

you will get error on this line also

Console.WriteLine("Line " + i + "'s first value is: " + itemLines[i][0]);

If previous statement does not having data to split itemLines[i][0] is going to be null, to solve this do check having element on particular node using if statement

if(itemLines[i]!=null && itemLines[i].Length>0)
Console.WriteLine("Line " + i + "'s first value is: " + itemLines[i][0]);