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.
Useful preparation · 1 prerequisite
Use this as a map, not a lock. If these ideas are familiar, continue.
- Depend on the behavior you need — Swap a game's damage rule or a storage implementation without changing the code that uses the behavior.
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.
- List<Player> stores Player elements; a generic result can preserve that element type instead of returning object.
- IReadOnlyList<T> exposes reading through this contract, but does not guarantee the underlying object can never change elsewhere.
- Dictionary<TKey,TValue> is useful for key lookup; TryGetValue makes the missing-key branch explicit.
- A constraint such as where T : IHasId permits access to that interface's members. Generics do not invent members on an unconstrained T.
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);- Infer T
First(names) uses T = string, so the returned value stays a string.
- Guard
The empty-list path is explicit rather than an unchecked index access.
- 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 →