LLearnCode
Academy/csharp/Collections and behavior

intermediate · 28 minute study

Generics keep a relationship intact across a reusable algorithm

Write one list helper that preserves element types, and select collection structures that match how you access the data.

Loading progressEvidence grows with practice
Useful preparation · 1 prerequisite

Use this as a map, not a lock. If these ideas are familiar, continue.

First, build a mental model

T is a type chosen for one use of a generic. The generic body must work for every allowed T. A constraint describes the capabilities the body is entitled to use.

  1. List<Player> stores Player elements; a generic result can preserve that element type instead of returning object.
  2. IReadOnlyList<T> exposes reading through this contract, but does not guarantee the underlying object can never change elsewhere.
  3. Dictionary<TKey,TValue> is useful for key lookup; TryGetValue makes the missing-key branch explicit.
  4. A constraint such as where T : IHasId permits access to that interface's members. Generics do not invent members on an unconstrained T.
Read the codecsharp · educational example
static T First<T>(IReadOnlyList<T> items)
{
    if (items.Count == 0) throw new InvalidOperationException("Empty list");
    return items[0];
}

var names = new List<string> { "Ada", "Lin" };
string first = First(names);
var scores = new Dictionary<string, int> { ["p1"] = 12 };
bool found = scores.TryGetValue("missing", out int score);
Console.WriteLine(first);
Console.WriteLine(found);
  1. Infer T

    First(names) uses T = string, so the returned value stays a string.

  2. Guard

    The empty-list path is explicit rather than an unchecked index access.

  3. Lookup

    The missing key produces found=false; callers must inspect the boolean.

Production thinking

Take this beyond the example.

Use explicit not-found contracts and bound collection sizes from external data. Keep IDs distinct from list positions; avoid unnecessary repeated scans when a keyed lookup fits.

Sources and further reading

Your evidence

unseen is a local learning signal, not a credential or proof of production competence.

Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.

Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.

Next lesson · Functions can be values, and subscriptions have lifetimes →