0

I have two methods in class Game.

public Player WhoWins(Player player)
    {
        for(int row = 0; row < Board.Length; row++) {
            for(int col = 0; col < Board.Length; col++)
            {
                //Horizontal Win
                if (Board[col, 0] == player.X_Or_O || Board[col, 1] == player.X_Or_O || Board[col, 2] == player.X_Or_O)
                {
                    return player;
                }
                //Vertical Win
                else if (Board[0, row] == player.X_Or_O || Board[1, row] == player.X_Or_O || Board[2, row] == player.X_Or_O)
                {
                    return player;
                }
                
                //Diagonal Win
                else if(Board[col, row] == player.X_Or_O || Board[col, row--] == player.X_Or_O)
                {
                    return player;
                }
                

            }
        }
        return null;
    }

    public bool PlayerMove(Player player, int x, int y)
    {
        if(x > 2 || y > 2)
        {
            System.Console.WriteLine("The idex is incorrect.");
            System.Console.WriteLine("Try Again!");
        }
        else
        {
            Board[x, y] = player.X_Or_O;

            **var win = WhoWins(player);**

            return win is not null;
        }
        return default;
    }

When I run the code, the bolded code(var win = WhoWins(player);) line stops it. The bug says: 'System.NullReferenceException: 'Object reference not set to an instance of an object. This exception was originally thrown at this call stack: TicTacToe.Implementations.Game.PlayerMove(TicTacToe.Implementations.Player, int, int) in Game.cs' What do I do know and how can I fix this?

I fixed it by checking if 'player' passed to 'PlayerMove' is null or not.

0 Answers0