C# and .NET • Modern C# baseline
Designing Stable C# APIs
Expose contracts that communicate ownership, nullability, errors, and compatibility.
A public API becomes a long-term contract for its callers. Use clear types, nullable annotations, asynchronous suffixes for async methods, and cancellation tokens when operations may be long-running. Avoid returning mutable internal collections and avoid adding overloads that make common calls ambiguous.
Key points
- Use XML documentation for public library members where appropriate.
- Prefer additive changes and test compatibility for widely consumed packages.
Example
public interface IInvoiceReader
{
Task<Invoice?> FindAsync(
string invoiceId,
CancellationToken cancellationToken = default);
}
What to expect
The signature communicates asynchronous lookup, possible absence, and caller-controlled cancellation.
Practice exercise
Decide how invalid IDs and service failures are reported without conflating them with a missing invoice.
Key idea: Good APIs make common valid use straightforward and failure behavior explicit.