I’m working on a program that feeds a number (int) to a 2D array.
That part is easy, but my professor added that the program should be able to determine where the number was added from, via string (usually, it’s a letter).
Normally, I simply would’ve converted the int 2D array into a string one, concatenated the string to the number, and say job is done.
But the professor gave us an “Oh crap” moment when he mentioned it had to be done using a class.
I’m not very knowledgeable in classes, I’ve only used them ever to pass one variable in one form to another, via the get/set method.
Basically, what the professor wants is for the Array to contain both the int, and the string, in the same index, something like this:
The class:
class ClassName
{
public int num;
public string loc;
}
The main program:
public frmSGame()
{
InitializeComponent();
}
ClassName[,] myArray = new ClassName[9,8];
public frmMain_Load(object sender, EventArgs e)
{
clearArray();
}
public void clearArray()
{
for (int y = 0; y < 8; i++)
{
for (int x = 0; x < 9; j++)
{
myArray[x, y].num = -1;
myArray[x, y].loc = "A";
}
}
}
And there lies my problem. Running the program yields me a “NullReferenceException was unhandled – Object reference not set to an instance of an object”, at the for int loop in the clearArray() function.
I’m really not sure what I did wrong. Putting the “ClassName[,] myArray = new ClassName[9,8]” inside the clearArray() function did nothing, and since I need to modify the array in multiple functions, I’m pretty sure putting that in every function would lead to disastrous results.
Might I have some help / advice in this, please?
The declaration
ClassName[,] myArray = new ClassName[9,8];makes an array with spaces for 72 objects, but it doesn’t make 72 objects. The array is empty to start with.Before you try to do anything with the objects in the array (e.g. access
numorloc) you need to actually create them. You could do it inside your inner loop here: