0

im writing a simple chess game with c# and cant figure out what im doing wrong here. Box class represents a square on the board.

     public class Board
            {
                Box[,] boxes;
                public Board()
                {
                    Box[,] boxes = new Box[8, 8];
                    
                }
                public void Setpieces()
                {
                    this.boxes[0, 0].SetEmpty(false);
                }

then i create a board Board boxes = new Board(); and call setpieces boxes.Setpieces(); and i get an error saying object reference not set to an instance of an object. im sure whatever ive done wrong is obvious but ive spent a while trying to figure it out and cant get it, so any help would be appreciated.

bjizz
  • 1
  • 2
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Timothy G. Jul 05 '21 at 15:34
  • `Box[,] boxes = new Box[8, 8];` doesnt instantiate all the `Box` instances in the array. It just allocates an array (of nulls, assuming `Box` is a reference type) – Jamiec Jul 05 '21 at 15:35
  • @TimothyG. unfortunately not, because i know the issue is the object is null, i just cant figure out why. it seems like my board class isnt being initialised, but im not sure why not. – bjizz Jul 05 '21 at 15:36
  • In constructor you have set new local variable instead of your property one. Change `Box[,] boxes = new Box[8, 8];` to `boxes = new Box[8, 8];` – Azelski Jul 05 '21 at 15:36
  • @xdjiijii , thanks for replying, ive just changed it to this public class Board { Box[,] boxes; public Board() { boxes = new Box[8, 8]; } and its given me a new error, "ambiguity between Board.boxes and Board.boxes" – bjizz Jul 05 '21 at 15:41
  • Have another look at my comment above. `this.boxes[0, 0]` (and all other elements) are null when you try to call `SetEmpty` method – Jamiec Jul 05 '21 at 15:43
  • @Jamiec ok, i think i misunderstood originally, i will implement that now, thank you for reiterating – bjizz Jul 05 '21 at 15:49

0 Answers0