C# Refreasher: Dictionaries!

addam davis
3 min readMar 25, 2022

Objective: Understand and Implement a dictionary!

Dictionaries are similar to lists; however, dictionaries are associated by key value pairs. This means with a list we just shovel a bunch of objects in it and sort through it. With a dictionary you associate objects with values with a key value pair.

Let’s take a look at declaring it with an item class. Dictionaries allow you to associate a key with an item and just by using that key retrieve that item. How do we declare a dictionary?

public Dictionary <TKey, TValue> These are generic values.

we are going to associate our item ID’s with our items. we are going to have the key be the int value. That is how we want to associate that object. The value that is going to be associated is an item type.

public Dictionary<int, Item>

Every dictionary, just like every variable needs a name.

We declare this as a new dictionary.

Now let’s take a look at how to populate this dictionary. Inside the void start we call the dictionary with the add function and give it key and a value.

If we wanted to define the item before you add it to the dictionary you can. We are using the same items class we used in a previous tutorial.

Now we could keep the key value at 0 or we could use sword.id. Ideally you would just use 0 and increment from there. The item we are going to associate 0 with is the sword from above.

Now that we have a dictionary established how do we actually use these items? The same way to retrieve them is the same way as a list.

This is looking for a key, and it is going to return an Item. We can store this in a value Items.

By doing this we can access the item’s name or ID. We now have access to whatever Item is associated to that key. Don’t be afraid to experiment with your dictionaries and I’ll see you in the next tutorial!

--

--