LLearnCode
Academy/csharp/Trust boundaries and asynchronous work

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.

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

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.

  1. int? represents an optional int value. string? is a nullable reference annotation used by static analysis when enabled.
  2. TryParse exposes ordinary parsing failure without an exception-based normal path.
  3. A null-forgiving ! suppresses compiler warnings at that expression; it does not check or repair a runtime null.
  4. Catch the failures you can handle. Use throw; to rethrow the current exception without replacing its original stack information.
Read the codecsharp · educational example
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");
  1. Parse

    The word zero is not an integer literal; TryParse returns false.

  2. Represent failure

    ParsePositive returns null instead of inventing a valid quantity.

  3. 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 →