C#

Michal Slotwinski
Michal Slotwinski
3,378 Points

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
7,348 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.

Michal Slotwinski
Michal Slotwinski
3,378 Points

Thank You Emmanuel, this fixed my problem!