Question about Error NullREferenceException


New member
Nov 30, 2016
Programming Experience
So I was working on a game that I am making to teach myself how to code, everything was going fine until I compiled, found a room was not linked to the other room and trapping the player in said room, I exited the program and went back to the code and went to make the changes needed, once I finished I hit the start button to ensure the changes worked. Thats when I started getting the error. Here is the code that I am getting the error at, I have not touched this particular piece of code in some time so it confuses me as to why its suddenly throwing an exception, I also have not edited any code related to what this is checking.

public bool HasRequiredItemToEnterThisLocation(Location location)
            if (location.ItemRequiredToEnter == null)
                // There is no required item for this location, so return "true"
                return true;

            // See if the player has the required item in their inventory
            return Inventory.Any(ii => ii.Details.ID == location.ItemRequiredToEnter.ID);

If you need more info let me know and I will be happy to provide it. Thank you.
It is throwing exception because you are trying to use something there that is a null reference. Debugger should show you what.
For example if 'location' is null then you can't access its .ItemRequiredToEnter member, that would be like calling <null>.ItemRequiredToEnter.
Anything before a '.' could be null and will throw NullReferenceException if it is. Another example "ii.Details.ID", if Details here is null then ii.<null>.ID throw that exception also.
Okay I will go over the code to anything that may reference that, but I have no idea what could have happened to it as all I did was add the code to link the cafe to the hallway.

I will post back if I continue to have issues. Thanks
I have no idea what could have happened

Which is exactly why you use the debugger to watch the code as it executes rather than just reading it. When the exception is thrown, use the debugger to determine which reference is null. You can then look back through the code to see where you expected a value to be assigned. If you still can't determine why that reference is null then you should try again, this time setting a breakpoint where you expect the value to be set and stepping through the code from there to where the exception is thrown.
Top Bottom