Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

Battleship project exception

Hi,

I have only started working on this project but cant progress further due to exception throwing all the time.. Basically exception is thrown no matter what value method Onboard returns. Thank You for help.

https://github.com/MKslots/BattleShip/tree/master/BattleShipGame

1 Answer

Emmanuel C
Emmanuel C
10,636 Points

Hey Michal,

I think the problem is that the Width and Height properties of Board never get set. The setter of an auto property when you try to set it like

Width = 20;

Then because of how your setter is, it would ignore the 20 and set _width to PlayerBoardSize. But since you never set it anywhere, _width stay uninitialized and defaults to 0. so when you call onBoard(pointer) the argument must be 0 or else return false.

One of the neat things about C#'s auto property is not needing to declare the backing field as itll create it for you. A solution to this can be just suing a normal auto prop for width and height then set them in the constructor.

public int Width {get; private set; }
public int Height {get; private set; }

public Board(int playerBoardSize)
{
    PlayerBoardSize = playerBoardSize;
    Width = playerBoardSize;
    Height = playerBoardSize;
}

Hope this helps, good luck.

Thank You Emmanuel, this fixed my problem!