Lesson 6 of 10

Arrays and lists

Goal

A fixed-size array and a List<T> that grows

01

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.

02

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
  1. SlotAt returns the item at its index, counting from zero
  2. SlotAt returns an empty string outside the array without stopping the program
  3. AddItem adds the item at the end and returns true
  4. The bag never holds more than five items
  5. UseItem removes one copy and returns false for an item that isn't in the bag
  6. CountOf counts the copies of an item
03

Hints

0/3
Track lessons0 of 10 done

C# is the language behind Unity games and .NET apps. Every variable has a fixed type, programs are built from classes, and it comes with ready-made tools for most of what you need.

Beginner level, 10 lessons, 2.5 hours in total.

Program.cs
OutputC# (Mono 6.6, Judge0)

Compiling and running your code on the server.

–/6

Compiling and running your code on the server.

6 checks listed under “Your task”.

Track lessons0 of 10 done

C# is the language behind Unity games and .NET apps. Every variable has a fixed type, programs are built from classes, and it comes with ready-made tools for most of what you need.

Beginner level, 10 lessons, 2.5 hours in total.