Skip to main content
C# for Games – Complete Beginner to Advanced Guide
CHAPTER 06 Beginner

Arrays, Lists, and Collections

Updated: May 16, 2026
25 min read

# CHAPTER 6

Arrays, Lists, and Collections

1. Introduction

A variable holds one piece of data. string weapon = "Sword";. But what if your player has a backpack that holds 20 weapons? Creating 20 individual variables (weapon1, weapon2, etc.) is horrible programming practice. To store massive groups of data, we use Data Structures. In C#, the three most common structures used in game development are Arrays, Lists, and Dictionaries. In this chapter, we will master Collections. We will learn how to store fixed groups of items in Arrays, create dynamic expanding inventories using Lists, and map key-value pairs using Dictionaries.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Declare, initialize, and access data in an Array.
  • Understand the Zero-Index rule of programming.
  • Use a List<T> to create dynamic, resizable collections.
  • Use a Dictionary<TKey, TValue> for ultra-fast data lookups.
  • Iterate through collections using foreach loops.

3. Arrays (The Fixed Box)

An Array is a collection of variables of the *same type* stored in a continuous block of memory.
  • *Limitation:* You must define exactly how big the array is when you create it. It cannot grow or shrink later!
  • Arrays are incredibly fast, making them perfect for fixed data (e.g., 4 players in a split-screen game, or 6 slots in a revolver).
csharp
123456789
// Create an array that holds exactly 3 strings
string[] inventory = new string[3];

// Add items (Programming starts counting at Zero!)
inventory[0] = "Sword";
inventory[1] = "Shield";
inventory[2] = "Potion";

Console.WriteLine("Equipped: " + inventory[0]); // Prints "Sword"

4. Lists (The Expanding Backpack)

A List is the most commonly used collection in modern game dev. Unlike Arrays, Lists can dynamically grow and shrink. If a player picks up 50 apples, the List simply expands.
  • *Requirement:* You must add using System.Collections.Generic; at the top of your script.
csharp
1234567
List<string> backpack = new List<string>();

backpack.Add("Sword");
backpack.Add("Health Potion");
backpack.Remove("Sword"); // The list automatically shrinks!

Console.WriteLine("Items in bag: " + backpack.Count);

5. Dictionaries (The Key-Value Map)

What if you want to look up an enemy's health by their name? Searching through a List of 1,000 enemies takes time. A Dictionary solves this by pairing a "Key" with a "Value."
csharp
12345678
// Key is a String (Enemy Name), Value is an Int (Health)
Dictionary<string, int> bestiary = new Dictionary<string, int>();

bestiary.Add("Goblin", 50);
bestiary.Add("Dragon", 5000);

// Ultra-fast lookup!
Console.WriteLine("Dragon HP: " + bestiary["Dragon"]);

6. The foreach Loop

To read every item in a List or Array, you *could* use a standard for loop, but C# provides a much cleaner tool: the foreach loop.
csharp
123456
List<string> weapons = new List<string>() { "Axe", "Bow", "Dagger" };

foreach (string w in weapons)
{
    Console.WriteLine("You have a: " + w);
}

7. Visual Learning: The Index Concept

txt
1234
[ ARRAY: string[] inventory = new string[4]; ]

Index:    [0]         [1]         [2]         [3]
Data:  [ "Sword" ] [ "Bow" ]   [ NULL ]    [ NULL ]

*Note: If you try to access inventory[4], the game will instantly crash with an "Index Out Of Bounds" exception!*

8. Best Practices

  • Use Lists for Gameplay, Arrays for Performance: If you are spawning and deleting enemies constantly, use a List. If you are building a voxel engine (like Minecraft) holding exactly 16x16x16 blocks, use an Array. Arrays are slightly faster for the CPU to read.

9. Common Mistakes

  • Index Out of Range Exception: The most common bug in programming. If an Array has 3 items, the slots are 0, 1, 2. If you ask the computer for slot 3, it looks outside the allocated memory and crashes the program. *Always remember: Length is 3, but the highest Index is 2!*

10. Mini Project: Build an RPG Inventory

Objective: Create a dynamic List and iterate through it.
  1. 1. Open your Console project. Write the following:
csharp
1234567891011121314151617181920212223242526272829
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 1. Create a dynamic List
        List<string> inventory = new List<string>();

        // 2. Player loots a chest
        Console.WriteLine("Looting chest...");
        inventory.Add("Iron Sword");
        inventory.Add("Health Potion");
        inventory.Add("Gold Coin");

        // 3. Player drinks a potion
        Console.WriteLine("Drinking potion...");
        inventory.Remove("Health Potion");

        // 4. Display Inventory
        Console.WriteLine("\n--- CURRENT INVENTORY ---");
        foreach (string item in inventory)
        {
            Console.WriteLine("- " + item);
        }
        Console.WriteLine("Total items: " + inventory.Count);
    }
}
  1. 2. Press Play. Watch the dynamic addition, removal, and rendering of the data!

11. Practice Exercises

  1. 1. What namespace must be included at the top of your script to use List<T> and Dictionary<TKey, TValue>?
  1. 2. If you declare int[] scores = new int[5];, what is the exact index number of the very last slot in that array?

12. MCQs with Answers

Question 1

You are programming an RPG where the player's backpack can hold anywhere from 0 to 999 items depending on what they pick up. Which data structure is best suited for this?

Question 2

You have a List<string> names containing 3 items. What happens if you try to execute Console.WriteLine(names[3]);?

13. Interview Questions

  • Q: Explain the fundamental difference in memory allocation between an Array and a List<T> in C#. When would you explicitly choose an Array over a List?
  • Q: Walk me through the concept of "Zero-Index" arrays. Why does array.Length return a number that is 1 higher than the maximum readable index?
  • Q: A game requires you to instantly look up the required crafting materials for an item simply by providing the item's name (e.g., passing "Iron Sword" instantly returns "2 Iron, 1 Wood"). Which Collection is best suited for this, and why?

14. FAQs

Q: Can a List hold custom Objects? A: Yes! A List can hold anything. List<Enemy> activeEnemies = new List<Enemy>(); is incredibly common. You can then use a foreach loop to call .TakeDamage() on every single enemy in the list at once!

15. Summary

In Chapter 6, we learned how to manage vast amounts of game data. We explored Arrays for strict, fast, fixed-size data blocks. We unlocked the versatility of Lists to build dynamic, expanding inventories. We utilized Dictionaries for lightning-fast key-value lookups, and mastered the foreach loop to easily iterate through our collections. We no longer write 50 variables; we write one List.

16. Next Chapter Recommendation

Our code is solid, but it only runs once and then stops. A game is a continuous simulation. Proceed to Chapter 7: Game Loops and Time Management.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·