Lesson 42 +10 XP

Collections & Generics

Collections are containers for groups of objects. The most useful ones are generic - they work with any type.

List<T>

A List<T> is like a resizable array:

Code

csharp
using System.Collections.Generic;

### List<string> cars = new List<string>();
cars.Add("Volvo");
cars.Add("BMW");

### Console.WriteLine(cars[0]);   // Volvo
cars.Remove("Volvo");

### Console.WriteLine(cars.Count);  // 1

The &lt;T&gt; means generic

The &lt;T&gt; in List&lt;T&gt; is a type parameter. List&lt;int&gt;, List&lt;string&gt;, and List&lt;Car&gt; are all lists, but each holds only its own type. This gives you type safety - the compiler stops you from mixing types.

Dictionary&lt;TKey, TValue&gt;

A dictionary stores key/value pairs for fast lookups:

Code

csharp
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Ada"] = 36;
ages["Grace"] = 85;

### Console.WriteLine(ages["Ada"]);   // 36

Other common collections

  • HashSet&lt;T&gt; - unique values, no duplicates.
  • Queue&lt;T&gt; - first-in, first-out.
  • Stack&lt;T&gt; - last-in, first-out.
  • LinkedList&lt;T&gt; - fast insertions in the middle.

Arrays vs List

  • Array: fixed size, great when you know the count.
  • List&lt;T&gt;: grows and shrinks automatically, more flexible.

TL;DR

  • List&lt;T&gt; is a resizable, type-safe array.
  • &lt;T&gt; makes a collection generic (works with any type).
  • Dictionary&lt;TKey, TValue&gt; stores key/value pairs.
  • Use using System.Collections.Generic; to access them.