LLearnCode
Academy/csharp/Read and write small programs

beginner · 23 minute study

Guard invalid cases before repeating useful work

Most practical programs decide which inputs qualify and apply the same rule to each qualifying item. A misplaced condition can silently corrupt a summary.

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

An if statement opens one gate. A loop revisits a block with a changing item or index. Keep the eligibility rule separate from the accumulated result.

  1. if and switch choose behavior; their conditions and branches should express a rule you can say aloud.
  2. foreach is a clear default when you need each element without changing the collection's structure.
  3. for exposes initialization, continuation condition and update; a zero-based array's last valid index is Length - 1.
  4. continue skips this iteration; break ends the loop. Short-circuit && and || can prevent an unsafe second operation.
Read the codecsharp · educational example
int[] quantities = { 2, 0, 3, -1 };
int acceptedUnits = 0;
foreach (int quantity in quantities)
{
    if (quantity <= 0) continue;
    acceptedUnits += quantity;
}
Console.WriteLine(acceptedUnits);
  1. 2

    Positive: add 2, so acceptedUnits becomes 2.

  2. 0

    The guard skips zero without ending the loop.

  3. 3 and -1

    Add 3, then skip -1. The result is 5.

Production thinking

Take this beyond the example.

Test zero items, one item, invalid items and a last-element boundary. For repeated writes, decide whether invalid data should be rejected as a batch instead of silently skipped.

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 · Methods make input, output and responsibility visible →