Lesson 21.1 – Adding a price to game items

If we want the player to be able to buy and sell items, we need to add prices to each Item object.


Step 1: In the Engine project, edit the Item.cs class.

Add an integer “Price” auto-property to the class, add a price parameter to the constructor, and set the Price property’s value in the constructor.

The Item class should look like this now:


Step 2: Now that the Item constructor requires a price parameter, we need to change the classes that use Item as their base class – Weapon and HealingPotion.

We will change their constructors to accept a “price” parameter, and pass it to the base (Item) class constructor. This is how they should look now:






Step 3: The next change will be to the World class, where we create instances of the items. Change the PopulateItems() function to this (you can use your own prices for the items):


NOTE: For the Adventurer pass, we set the item’s value to -1. We’re going to use that as a “flag” (indicator) value. In our code to display the player’s items, we won’t include any items that have a value of -1. Those will be unsellable items.


Step 4: So you can see how I think when I’m programming, I left the “Note” in step 3.

However, if I need to add a note for the lesson, that might also mean something is not clear in the code. I don’t want to make a change in the future, and forget why some items have a value of -1.

This is a “code smell” – a sign that the source code may have a problem.

Let’s make this easier to understand.

In the World class, add this new class-level, public constant, near the other constants at the top of the class:

Then, change the Adventurer pass line in PopulateItems() to this:

Now, it is very clear that we don’t want the player to be able to sell adventurer passes. We won’t ever be confused by a “magic number” – a hard-coded value that has a special meaning.


Step 5: Run your program, and make sure it still works. Right now, you won’t see the price anywhere. But, it’s good to check your program after each change.


Source code for this lesson

Source code on GitHub

Source code on Dropbox


Next lesson: Lesson 21.2 – Create the vendor class and add it to locations

Previous lesson: Lesson 21.0 – Plans for adding a vendor to locations

All lessons: Learn C# by Building a Simple RPG Index

2 thoughts on “Lesson 21.1 – Adding a price to game items

  1. Thanks for this tutorial! I’m running into a strange problem here: I have added the property Price in just the right way to the Item class, and the Weapon and HealingPotion constructors both ask for it as part of the base, but when I add ‘price’, it’s not recognised. I checked my spelling and everything, but it won’t go away. Would you happen to know what the problem might be?

Leave a Reply

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