none
class creation NULL reference RRS feed

  • Question

  • Hi,

    I have the below 2 classes defined.

       public class Position
        {
            public Position (Boolean occupied, int player, int boardNumber, int[] neighbours )
            {
                this.occupied = occupied;
                this.player = player;
                this.boardNumber = boardNumber;
                this.neighbours = neighbours;
            }
            public Boolean occupied { get; set; } // is occupied by a piece?
            public int player { get; set; } // black or white
            public int boardNumber { get; set; }
            public int[] neighbours;

        }

        
        public class Board
        {
            public List<Position>  positions;
           // private Position pos1;

            public Board(List<Position> positions)
            {

                this.positions = positions;
            }

            public Board()
            {
                List<Position> positions = new List<Position>();
            }
     }
     
      Main()
            {

                //    Board listOfPos1 = new Board();
                Board theBoard = new Board();

                List<Position> listOfPos = new List<Position>();

                int[] values = new int[] { 2, 4, 5 };
                Position pos1 = new Position(false, 0, 1, values);
                listOfPos.Add(pos1); // works ok

                theBoard.AddPos(pos1); // Fails with Additional information: Object reference not set to an instance of an object.

    I don't understand why fails in the line in Bold!. I initialise theBoard  variable and then try to use the method. A similar way with the List<Position> listOfPos  works fine. Any ideas what I am doing wrong?

    Thanks!




    • Edited by panlondon Friday, September 21, 2018 1:52 PM
    Friday, September 21, 2018 1:46 PM

Answers

  • Hi, because this.positions is null. Instead of Board theBoard = new Board(); use constructor with parameter new Board(listOfPos)

    List<Position> listOfPos = new List<Position>();
    
    Board theBoard = new Board(listOfPos);
    
    int[] values = new int[] { 2, 4, 5 };
    Position pos1 = new Position(false, 0, 1, values);
    listOfPos.Add(pos1); // works ok
    
    theBoard.AddPos(pos1);


    • Marked as answer by panlondon Friday, September 21, 2018 2:20 PM
    Friday, September 21, 2018 2:07 PM