C# C# Objects Encapsulation and Arrays Null Reference

Josh Gallacher
PRO
Josh Gallacher
Pro Student 3,325 Points

My code will only return the location at index number 6 no matter the number I put in to 'path.GetLocationAt()'

I've gone over the code a few times now and it looks identical to the one in the video. I've also checked to see if I've left any lingering values somewhere that the code is unintentionally grabbing but can't seem to find any. It also tells me "5,2 is outside the boundaries of the map!" which it shouldn't be. Does anyone have any idea as to what might be causing this?

Edited to include a link to the code snapshot here: https://w.trhou.se/wixz9cqx9n

andren
andren
28,432 Points

It's impossible to help you without seeing your code, even if it looks identical to you there is almost certainly some small typo or inconsistency somewhere, they can be extremely hard to spot.

I would recommend that you take a snapshot of your current workspace. You can do that by clicking on the camera icon found in the upper-right corner of the workspace window. Once you have created a snapshot you can share the link to it in a post here.

If you do that then I will take a thorough look at your code.

Josh Gallacher
Josh Gallacher
Pro Student 3,325 Points

Oops, forgot to add the snapshot link. Sorry about that, thank you.

https://w.trhou.se/wixz9cqx9n

1 Answer

andren
andren
28,432 Points

Alright after quite some digging I belive I have found the issue. The problem lies in the constructor of the Point class:

public Point(int y, int x)
{
  Y = y;
  X = x;
}

You define the parameters to be y and x. The parameters should be x and y, since parameters are assigned based on their position the order that they appear matter quite a bit.

With that mix up you end up with the Point object having a Y property being set to what is supposed to be it's X value and vice versa.

So when it gets passed 5, 2 it actually creates a point at 2, 5 which is outside the boundary of the map. The reason why the error message states 5, 2 instead of 2, 5 is that it gets its x and y value from the parameters of the MapLocation constructor which has them in the right order. While the OnMap function looks at the properties which has been set through the Point constructor which MapLocation inherits from.

If you fix the order like this:

public Point(int x, int y)
{
  Y = y;
  X = x;
}

Then your code should work correctly. You shouldn't feel bad about not being able to debug this on your own, it was actually pretty though to identify the error, especially because of the confusing exception message it produced.

Josh Gallacher
Josh Gallacher
Pro Student 3,325 Points

Thanks so much for the help! Made the changes and everything is running as intended :)