intermediate · 28 minute study
Model absence before deciding whether to throw
A missing value, a rejected input and a broken dependency are different outcomes. Model them so callers can respond deliberately.
Useful preparation · 1 prerequisite
Use this as a map, not a lock. If these ideas are familiar, continue.
- A LINQ query can be a recipe rather than a snapshot — Read data pipelines without accidentally rerunning work or assuming that a deferred query already froze its result.
First, build a mental model
Nullable annotations help the compiler track possible absence. Runtime checks establish what the current value actually is. Exceptions carry failures across call boundaries; they should not be used to hide an expected branch.
- int? represents an optional int value. string? is a nullable reference annotation used by static analysis when enabled.
- TryParse exposes ordinary parsing failure without an exception-based normal path.
- A null-forgiving ! suppresses compiler warnings at that expression; it does not check or repair a runtime null.
- Catch the failures you can handle. Use throw; to rethrow the current exception without replacing its original stack information.
static int? ParsePositive(string? text)
{
if (!int.TryParse(text, out int value) || value <= 0) return null;
return value;
}
int? parsed = ParsePositive("zero");
if (parsed is int quantity)
Console.WriteLine(quantity * 2);
else
Console.WriteLine("Invalid quantity");- Parse
The word zero is not an integer literal; TryParse returns false.
- Represent failure
ParsePositive returns null instead of inventing a valid quantity.
- Narrow
The int pattern fails, so the caller handles the invalid-input branch.
Production thinking
Take this beyond the example.
Enable nullable analysis in the project and handle compiler feedback deliberately. Decode external JSON at runtime; annotations do not certify payloads received from other systems.
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 · A Task represents completion, not a promise of another thread →