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.
Useful preparation · 1 prerequisite
Use this as a map, not a lock. If these ideas are familiar, continue.
- A declared type is a contract for every assignment — Read a C# program without treating its extra syntax as decoration. Understand which mistakes are caught before execution and which remain your responsibility.
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.
- if and switch choose behavior; their conditions and branches should express a rule you can say aloud.
- foreach is a clear default when you need each element without changing the collection's structure.
- for exposes initialization, continuation condition and update; a zero-based array's last valid index is Length - 1.
- continue skips this iteration; break ends the loop. Short-circuit && and || can prevent an unsafe second operation.
int[] quantities = { 2, 0, 3, -1 };
int acceptedUnits = 0;
foreach (int quantity in quantities)
{
if (quantity <= 0) continue;
acceptedUnits += quantity;
}
Console.WriteLine(acceptedUnits);- 2
Positive: add 2, so acceptedUnits becomes 2.
- 0
The guard skips zero without ending the loop.
- 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 →