Search code examples
c#constructorinitializationtext-based

Why is my Player property in QuestGUI returning null despite initialization in the Game constructor?


I am implementing an text-based game in C#. In the "Game"-class, I am initializing a player. If this player completes a quest, he would earn some rewards. Therefore, I want to give the initialized player to another class called QuestGUI.

The constructor of the game class:

        public Game()
        {
            Item[] initialItems = new Item[]
            {
                new Weapon("Sword", 10),
            };
            main_player = new Player("Omegar", 100, initialItems);

            Quest[] quests = new Quest[]
            {
                new Quest(...);
            };

            QuestHub QuestHub = new QuestHub(quests);
            QuestGUI = new QuestGUI(QuestHub);
            QuestHubGUI = new QuestHubGUI(QuestHub);

            QuestGUI.Player = main_player;
        }

Here is what I want to do in the QuestGUI class:

                QuestHub.DisplayResult(quest, input);

                Item reward = Player.GenerateItem();
                Player.AddItem(reward);
                Player.ReceiveItemMessage(reward);

The constructor of the QuestGUI-class:

        public Player Player { get; set; }
        public QuestHub QuestHub { get; set; }

        public QuestGUI(QuestHub questHub)
        {
            QuestHub = questHub;
        }

I tried to run what I described above. I expected the program to first display the result of the quest and then give the player a generated item. Instead, I got the following exception:

System.NullReferenceException: "Object reference not set to an instance of an object."

lb426_test.QuestGUI.Player.get returned null.


Solution

  • You declared main_player in the Game class. In the QuestGUI class, you have declared the property Player, which is not initialized in the constructor of QuestGUI. You have to add the player as a constructor parameter and initialize it.

        public Player Player { get; set; }
        public QuestHub QuestHub { get; set; }
    
        public QuestGUI(QuestHub questHub, Player player)
        {
            QuestHub = questHub;
            Player = player;
        }
    

    Then you need to adjust the constructor in the Game class to

        public Game()
        {
            Item[] initialItems = new Item[]
            {
                new Weapon("Sword", 10),
            };
            main_player = new Player("Omegar", 100, initialItems);
    
            Quest[] quests = new Quest[]
            {
                new Quest(...);
            };
    
            QuestHub QuestHub = new QuestHub(quests);
            QuestGUI = new QuestGUI(QuestHub, main_player);
            QuestHubGUI = new QuestHubGUI(QuestHub);
    
            QuestGUI.Player = main_player;
        }