Newbie coder here. Working on a game of Yahtzee but can't figure out why I'm getting this error (object reference not set to instance of object) when I have corrected it already. My 'form' object is null even though I've declared an instance of it in the class constructor and a green line saying it is not being used appears.
public partial class Form1: Form {
public Form1() {
InitializeComponent();
}
private Game game;
public void ShowMessage(string message) {
lblMessage.Text = message;
}
public void StartNewGame() {
game = new Game(this);
}
private void btnRoll_Click(object sender, EventArgs e) {
game.RollDice();
}
class Game {
private Form1 form;
public Game(Form1 form) {
form = new Form1();
}
public void RollDice() {
form.ShowMessage("blahblah");
}
The "NullReferenceException" error appears over form.ShowMessage and I don't know why. I have declared a new instance of the form class in the game constructor which is run when the player selects StartNewGame which runs the StartNewGame method. The easiest way to get it working is to simply add "Form1 form" to the parameter of the RollDice() method in the Game class, and then game.RollDice(this) in the Form1 event handler. But the instruction guide for the assignment states that we shouldn't do that and we are to initialize the Form1 object in the constructor of Game. Please help I'm new and cant understand why this is happening.