Lesson 6 of 10
Arrays and lists
- 14 min
- 6 checks
- 3 hints
- Go to task
Goal
A fixed-size array and a List<T> that grows
Explanation
An array holds a fixed number of slots that you set when you create it, like string[] hotbar = { "Sword", "Bow", "Potion" };. You read each slot by its position number, its index, and counting starts at zero: the first slot is hotbar[0], the number of slots is hotbar.Length, and the last index is Length - 1. If you ask for an index outside that range, the program throws an IndexOutOfRangeException. new int[5] creates five slots that each hold zero.
A List<T>, on the other hand, grows and shrinks as you need, and T is the type of its items, as in var bag = new List<string>();. Add puts an item at the end, Remove deletes only the first matching item and returns true if it found one, Contains tells you whether an item is there, and Count gives you the number of items, so use Count with a list and Length with an array. You go through the items with foreach (string item in bag), but don't add to the list or remove from it inside that loop, or the program throws an InvalidOperationException.
When you pass a list to a method, the method gets the list itself, not a copy, so whatever the method adds to it shows up for the caller without any need for ref, unlike the int in the previous lesson.
Your task
Complete SlotAt(hotbar, index) to return the item at the given index, or an empty string "" if the index is outside the array. Then complete AddItem(bag, item) to add the item and return true as long as the bag holds fewer than 5 items, and otherwise to leave it out and return false. Finally, complete UseItem(bag, item) to remove one copy of the item and return whether it was there, and CountOf(bag, item) to count, with foreach, how many copies of the item are in the bag.
Checks
6 checks- SlotAt returns the item at its index, counting from zero
- SlotAt returns an empty string outside the array without stopping the program
- AddItem adds the item at the end and returns true
- The bag never holds more than five items
- UseItem removes one copy and returns false for an item that isn't in the bag
- CountOf counts the copies of an item