Collections

7. Collections#

Arrays have fixed sizes. When the amount of data is unknown or changes at runtime, C# provides dynamic collection types. This chapter covers List<T> and Dictionary<TKey, TValue> — the two most widely used collections.

Why this chapter matters

Real programs rarely know in advance exactly how many items they will process:

  • a list grows or shrinks as items are added or removed

  • a dictionary maps keys to values for fast lookup

  • generics enforce type safety while keeping collections reusable

  • built-in methods handle common tasks: sorting, searching, filtering

Learning goals

By the end of this chapter, you should be able to:

  • create and populate List<T> with Add, Remove, and Contains

  • use Dictionary<TKey, TValue> to store and retrieve key-value pairs

  • iterate over collections with foreach

  • choose between List and Dictionary based on access pattern

Chapter flow