advanced · 29 minute study
Decode data and release resources at explicit boundaries
Build import/export utilities without treating a successfully deserialized file as automatically valid domain data.
Useful preparation · 1 prerequisite
Use this as a map, not a lock. If these ideas are familiar, continue.
- Cancellation is a request; stale results still need a guard — Stop wasting work after a user leaves a screen and prevent an older search response from replacing a newer one.
First, build a mental model
A file handle is a resource with a lifetime. JSON is external data with a shape and meaning that may differ from your current model. Release the resource and validate the data as two separate responsibilities.
- using disposes an IDisposable resource when its scope ends, including when an exception leaves the scope.
- Use await using for an IAsyncDisposable resource when asynchronous disposal is appropriate; it is not a replacement for every using.
- DeserializeAsync<T> can fail or produce null; matching C# types does not prove domain validity.
- Validate required fields and allowed ranges before turning a transport DTO into trusted application state. Avoid accepting arbitrary file paths from untrusted input.
using System.Text.Json;
using var stream = File.OpenRead("player.json");
PlayerDto? dto = await JsonSerializer.DeserializeAsync<PlayerDto>(stream);
if (dto is null || string.IsNullOrWhiteSpace(dto.Name) || dto.Score < 0)
throw new InvalidDataException("Invalid player file");
Console.WriteLine(dto.Name);
record PlayerDto(string Name, int Score);
// Example file: {"Name":"Ada","Score":12}- Acquire
OpenRead returns a stream owned by this scope.
- Decode and validate
The code checks both an actual DTO and the name/score rules.
- Release
The using declaration disposes the stream when the scope ends, even on rejection.
Production thinking
Take this beyond the example.
Version persisted schemas, bound import sizes and preserve a recoverable prior state. Test malformed JSON, missing fields, permission errors and interrupted writes using synthetic files.
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 deterministic test controls the sources of uncertainty →