0

Basically I created a class, and made a matrix out of that class and tried to give the property of that a class a certain name.

I've tried initializing it already but it still doesn't work

    public class Tile
    {
        public string TileName { get; set; }
        public int Status { get; set; }
    }
public class ChessBoard
    {
        private const int BOARDHEIGHT = 8;
        private const int BOARDWIDTH = 9;

        public Tile[,] InitializeBoard()
        {
            Tile[,] newBord = new Tile[BOARDHEIGHT, BOARDWIDTH];

            for (int x = 0; x < BOARDWIDTH; x++)
            {
                for (int y = 0; y < BOARDHEIGHT; y++)
                {
                    newBord[x, y].TileName = x+"-"+y;
                    newBord[x, y].Status = 0;
                }
            }
            return newBord;
        }

        public void DisplayBoard(Tile[,] Board)
        {
            for (int x = 0; x < BOARDWIDTH; x++)
            {
                for (int y = 0; y < BOARDHEIGHT; y++)
                {
                    Console.WriteLine(Board[x,y].TileName);
                }
                Console.WriteLine();
            }
        }

    }

        static void Main(string[] args)
        {
            ChessBoard CB = new ChessBoard();
            Tile[,] CBoard = CB.InitializeBoard();
            CB.DisplayBoard(CBoard);
        }

I wanted to try naming the Tile with its index, however I was only met with "System.NullReferenceException: Object reference not set to an instance of an object."

Gashio Lee
  • 119
  • 1
  • 15
  • 1
    You instantiated the array, but you haven't instantiated the elements in that array. For all `(x,y)` coordinates, `newBord[x, y]` is null. –  Jul 15 '19 at 13:31
  • Yea you need to instantiate each tile in that loop with newBord[x, y] = new Tile(); And also you have your height and width swapped in that loop. – Carter Jul 15 '19 at 13:49

0 Answers0