Lesson 10.4: Bug Fix – Removing multiple items from GroupedInventory

Mickey noticed a bug in the code, from the changes in Lesson 10.2, adding a GroupedInventory property for LivingEntity.

When we try to remove multiple items, like when completing a quest, it only removed one item. This lesson will fix the bug.



Lesson Steps

Step 1: Modify Engine\Models\LivingEntity.cs

There is a problem getting the “groupedInventoryItemToRemove” object on lines 147-148.

For unique items, we want to get the item that exactly matches the parameter. If a player has multiple swords (which will be unique items), we want to get the exact item, and remove it.

For non-unique items, we only need to get the GroupedInventory object with an ItemTypeID that matches the parameter’s ItemTypeID.

So, change lines 147-148 to this:

GroupedInventoryItem groupedInventoryItemToRemove = item.IsUnique ? 
GroupedInventory.FirstOrDefault(gi => gi.Item == item) : 
GroupedInventory.FirstOrDefault(gi => gi.Item.ItemTypeID == item.ItemTypeID);


This is a “ternary operator“. It evaluates the calculation before the question mark. If that calculation is “true”, it returns the first result (the part before the “:”). If it is “false”, it returns the second result (the part after the “:”).

It’s another way to do a simple “if…else” statement.

So, if the passed-in object is unique, we will look for the first item that completely matches it. If it is not unique, we will find the first item with the same ItemTypeID.



We really should have unit tests for this project. So, after I finish this batch of refactoring lessons, I’ll start creating those.


Return to main page

2 thoughts on “Lesson 10.4: Bug Fix – Removing multiple items from GroupedInventory

    1. There’s no real benefit. In fact, I would bet that both end up compiling into the exact same CLR (Common Language Runtime) code.

      I just like using the ternary operator when the condition of the “if” statement is not too long, and we’re only using the “if” to assign a value to a single variable. It’s fewer lines than writing an “if” statement with curly-braces (which is how I write all my “if” statements, to be consistent and clear), and slightly easier to understand the intent of the “if” (to set the value of a variable).

Leave a Reply

Your email address will not be published. Required fields are marked *