Serialization Contracts and Versioning
Design durable JSON contracts, distinguish transport models from domain models, evolve fields compatibly, and reject ambiguous or unsafe payloads.
Separate DTO and domain responsibilities
Evolve JSON without breaking consumers
Validate untrusted payloads safely
The short answer
A serialized contract is a public compatibility promise. Use explicit DTOs, stable names, clear required and optional semantics, tolerant additive evolution, and boundary validation before mapping data into domain objects.
Build the runtime mental model
Serialization converts object state to a transport representation; deserialization creates ordinary values from untrusted input. A domain object may enforce invariants or contain behavior that should not be coupled directly to wire-format choices.
Advanced C# work improves when you separate language syntax, runtime behavior, and application policy. Write down which layer owns the guarantee in this lesson. Then identify the observable evidence—a compiler rejection, test result, generated query, trace, or measurement—that would prove the model correct.
Design the boundary deliberately
Add optional fields with safe defaults, preserve stable field meanings, and use a version or new endpoint for incompatible changes. Define enum encoding, dates, time zones, numbers, nullability, and unknown-field behavior. Source generation can improve performance and trimming support.
The starter isolates one part of the mental model so it can run in the browser. The exercise moves the same rule into a current local .NET project where packages, framework hosting, diagnostics, and multi-file tests are available.
using System;
class ReportContract
{
public int Version { get; private set; }
public string Name { get; private set; }
public ReportContract(int version, string name)
{
Version = version;
Name = name;
}
}
class Program
{
static void Main()
{
var contract = new ReportContract(1, "report");
Console.WriteLine("version=" + contract.Version);
Console.WriteLine("name=" + contract.Name);
}
}Expected output
version=1 name=report
Diagnose failure and misuse
Renaming a property can break stored files and remote clients. Polymorphic deserialization can become a security risk if arbitrary runtime types are allowed. Accepting a syntactically valid payload without size and domain validation invites resource abuse.
Classify each failure as a contract violation, transient operational failure, permanent dependency response, concurrency conflict, or programmer defect. That classification determines whether to reject, retry, compensate, cancel, or fail fast. A generic catch-and-continue policy destroys the information needed to make that decision.
| Question | Evidence to inspect | Decision |
|---|---|---|
| Is the input valid? | Validation result and boundary examples | Reject with a stable contract |
| Is the failure transient? | Typed status, exception, and policy context | Retry only when bounded and safe |
| Is state still consistent? | Invariant and transaction outcome | Commit, compensate, or abort |
| Is performance acceptable? | Representative latency and allocation data | Keep simple or optimize one cause |
Apply the concept in production
Keep golden contract examples, compatibility tests, and migration fixtures. Log rejection categories without payload secrets. For durable events, prefer upcasters or explicit migration steps over teaching every domain type about every historical format.
Finish by making the result operable. Add structured diagnostics at the boundary, propagate cancellation, avoid sensitive data, and record SDK and dependency versions. Test the public behavior instead of private implementation details. If a framework or provider performs translation, serialization, concurrency, or I/O, include at least one test against the real production technology.
A senior-level review should be able to answer four questions: what contract is promised, who owns lifetime and cleanup, how failures become visible, and what evidence supports the design. If any answer depends on “the framework probably handles it,” inspect the documentation or runtime behavior and turn the assumption into a checked decision.
Quick knowledge check
Answer before you reveal.
01Why not serialize domain entities directly by default?
Transport compatibility and domain invariants evolve for different reasons; DTOs keep that boundary explicit.
02What must happen before adding complexity to this design?
State the requirement, preserve a correct baseline, collect evidence, and explain how the proposed mechanism improves a specific quality.
Exercise
Practice challenge
Define versioned order DTOs, map them into validated domain objects, and write compatibility tests for missing optional and unknown additive fields.
Requirements
- The implementation states its contract and ownership boundary explicitly
- Automated checks cover the successful path and at least two meaningful failures
- Diagnostics expose failure context without secrets or swallowed exceptions
- The project documents required SDK, packages, setup, run, and test commands
Optional extension: Measure or load-test the critical path and record whether the evidence justifies another optimization or abstraction.
Open in C# compilerLesson checkpoint
One small step locks it in
Mark this lesson complete, then keep the momentum going.
Clear up the details
Frequently asked questions
When should I use serialization contracts and versioning?
Use it when its explicit tradeoff solves a measured requirement or clarifies an owned boundary. Keep the simpler design when the additional mechanism does not improve correctness, operability, or changeability.
Does the browser compiler cover the complete production setup?
No. It runs the focused starter program. Framework, package, database, benchmark, and multi-project work requires a current local .NET SDK and the project commands described in the exercise.
What evidence should I keep after the exercise?
Keep the acceptance cases, automated tests, diagnostic or benchmark output where relevant, and a short decision note describing the chosen boundary and rejected alternative.