1.4.17 How to Write Null Checks

When something is null it means that it has been defined but nothing has been assigned to it. Null reference exceptions occur when something that is null tries to do something. It is common practice, then, to check if an object is null before doing anything with it. This prevents the application from unintentionally producing errors.

We want to give the TicketBooth Attendant the ability to eat food, but what if they don't have any food at all?


I've removed the code that assigns the Attendant food and will run the program.

A null reference exception occurs because we are trying to access the Weight field of the Attendant's Food object but they have none. This is called failing loudly.


Instead, we can fail silently by adding a conditional that checks if the object even exists. This is called a 'not null' check. To do this, take the object in question and use the != operator to compare it to null. In English you would say, "Ensure that the Food object is not the same as null".

If we run the program we can see that the conditional statement evaluates to false because the Food object is in fact null.

So if we press F11 the Eat method will never execute (it will fail silently), which is what we intended because the Attendant has no food and shouldn't be eating.

So now let's give the Attendant back their Food and run the application. Because the Food object is not null (it exists) the conditional will evaluate to true and the Eat method will execute.

Be careful with 'not null' checks, however, because the application will fail silently and there is a possibility you won't find bugs in your code.