0

I am currently trying to make monolopy as a little project. I am trying to create an Array of Tiles however when i run the code i get a nullreferenceException because Tile[] Tiles is showing as null. Any advice would be great.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Monolopy
{
class Board
{
     public Tile[] Tiles { get; }
     GoTile tile1;
     BuildingTile tile2;
     JailTile tile3;
     BuildingTile tile4;
     BuildingTile tile5;
     BuildingTile tile6;
     GoToJailTile tile7;
     BuildingTile tile8;
     BuildingTile tile9;
     ChanceTile tile10;
     BuildingTile tile11;
     BuildingTile tile12;



    public Board()
    {
        Tile[] Tiles = {
            tile1 = new GoTile(),
            tile2 = new BuildingTile(2, "Old Kent Road", 20, 200),
            tile3 = new JailTile(),
            tile4 = new BuildingTile(4, "WhiteHall", 40, 400),
            tile5 = new BuildingTile(5, "Euston Road", 50, 500),
            tile6 = new BuildingTile(6, "bow Street", 60, 600),
            tile7 = new GoToJailTile(),
            tile8 = new BuildingTile(8, "Strand", 70, 700),
            tile9 = new BuildingTile(9, "Fleet Street", 80, 800),
            tile10 = new ChanceTile(),
            tile11 = new BuildingTile(11, "Park Lane", 90, 900),
            tile12 = new BuildingTile(12, "Mayfair", 100, 1000)
        };
    }
}

}

2
  • 1
    Remove the Tile[] before Tiles, in your constructor, as you are populating your local variable Commented Apr 28, 2018 at 12:33
  • You define a second Tiles which only lives for the duration of the Board constructor. Remove the Tile[] from your board constructor to use the tile property instead. Commented Apr 28, 2018 at 12:36

2 Answers 2

1

You’re redeclaring Tiles in your constructor, so the instance property is never set. Just omit the Tile[] type in your constructor.

Also, add a (private) setter to the property.

Sign up to request clarification or add additional context in comments.

Comments

0

The Tile array in constructor is local variable in the constructor and so any code that uses property Tiles of the class Board will get null. The member Tiles is actually never initialized.

Try assigning the local variable's value to your property.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.