Null Reference
Now, we could call our GetLocationAt
method at Game
class.
In our class, we need to define the Path that be passed. Then, we call getLocationAt to define where is the position now.
try
{
Path path = new Path(
new[]
{
new MapLocation(0, 2, map),
new MapLocation(1, 2, map),
new MapLocation(2, 2, map),
new MapLocation(3, 2, map),
new MapLocation(4, 2, map),
new MapLocation(5, 2, map),
new MapLocation(6, 2, map),
new MapLocation(7, 2, map)
});
MapLocation location = path.getLocationAt(0);
Console.WriteLine(location.X + "," + location.Y);
}
catch (OutOfBoundsException ex)
{
Console.WriteLine(ex.Message);
}
It will return 0,2. It matches with our origin location (0,2). Now, try to change it to getLocationAt(8)
. It will throw Unhandled Exception
. What we have to do?
First, we have to look deeper at exception thrown. We could change it to:
catch (Exception ex)
{
Console.WriteLine("Unhandled Exception " + ex.Message);
}
Second, we could check if the MapLocation is true or false before print it. Therefore, we need conditional statement again.
MapLocation location = path.getLocationAt(8);
if (location!=null)
Console.WriteLine(location.X + "," + location.Y);