Maybe I'm missing something, but I've never fully understood exactly why I get these when I'm coding and usually assume I've got them covered, but it seems I'm struggling when I've got a class within a class and using arrays.
I normally manage to avoid these exceptions when I use something like this:
public Menu[] item = new Menu[4];
But stick that inside of another class (example with other declarations/method cut out):
public class GameMenu
{
public class Menu
{
public string name = "hello";
}
public Menu[] item = new Menu[4];
}
From here, I declare:
public GameMenu StartMenu = new GameMenu();
So, as I've got 5 instances here, I should be able to in theory declare them from within a method inside of the same class as the above line:
public void SetUp()
{
StartMenu.item[0].name = "New Game";
StartMenu.item[1].name = "Load Game";
StartMenu.item[2].name = "Options";
StartMenu.item[3].name = "Credits";
StartMenu.item[4].name = "Quit Game";
}
How, I end up with the Null Reference Exception. I suspect that the null references are the strings themselves, but I can't use:
StartMenu.item[0].name = new string; because it won't let me.
I'm wondering what exactly I'm missing here. I don't fully understand why these errors occur anyway. The C# documentation doesn't exactly make it clear to me.