I am getting an error called "System.NullReferenceException:" in my C # program.
I have searched on this website how to solve it and I have read that it is usually because the initialization is not used, so the values that it tries to access are "null".
However, I'm reviewing and I see that I initialize these values using the "new" (or at least I think I do).
This is the problematic fragment of the code:
public bool load(string fileName)
{
// Read the board from "fileName" and fill the _cells with its information
try
{
using (StreamReader sr = new StreamReader(fileName))
{
int validLines = 0;
int currentRow = 0;
string line = sr.ReadLine();
while (line != null)
{
if (validLines == 0)
{
int.TryParse(line, out _numRows);
validLines++;
}
else if (validLines == 1)
{
int.TryParse(line, out _numCols);
validLines++;
_cells = new Cell[_numRows, _numCols]; /*INICIALIZO LA ARRAY CELL*/
}
else
{
int currentCol = 0, j = 0;
for (int i = 0; i < _numCols; i++)
{
j++;
if ((line[j] > 0 && line [j] < 9) || line [j] == 'B' || line[j] == 'V')
{
_cells[currentRow, currentCol] = new Cell(CellState.Covered, line[j]); /*INICIALIZO CADA INSTANCIA DE LA ARRAY CELL*/
currentCol++;
}
else
{
i--;
}
}
currentRow++;
}
}
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read");
Console.WriteLine(e.Message);
return false;
}
return true;
}
public void print()
{
// Print the content of the board
for (int i = 0; i < _numRows; i++)
for (int k = 0; k < _numCols; k++)
{
Console.Write(" " + _cells[i, k].getContent());
//AQUÍ ES DONDE ME NOTIFICA QUE SUCEDE EL ERROR
}
}
Console.ReadKey();
}
Can someone locate where the error lies? I understand that for some reason the values in the array _cells [] remain as null, so when I apply the print () method the program peta and returns error.
Thank you.