Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,635 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!