13 Rules to Make AI Write Production-Grade C# Code
This article presents 13 engineering rules that turn AI-generated C# into production-ready code. It covers nullable reference types, records, switch expressions, async and cancellation practices, dependency injection and resource lifetime, strongly typed configuration, exception handling, and required tests, showing how to put these constraints into a project file so AI coding tools produce maintainable code.
Introduction: Why AI-Generated C# Code Compiles but Is Not Ready to Ship
When developers ask an AI coding tool to “add an endpoint that returns paginated orders for a customer,” the generated code is usually syntactically sound. Yet it often carries serious engineering risks: nullable reference warnings are ignored, async methods are written as blocking synchronous code, exceptions are caught too broadly, database contexts are reused as static fields, and configuration is read from scattered string keys. These problems rarely surface on a developer machine with a small dataset. In pre-production or production, they erupt as deadlocks, memory leaks, and corrupted data.
The answer is not to abandon AI assistance, but to give it a clear engineering contract. The 13 rules below can be written directly into a constraint file at the project root, where they act as hard boundaries for code generation.
1. Type System: Make Intent Verifiable by the Compiler
1. Enable Nullable Reference Types and Treat Warnings as Errors
Enable nullable reference types explicitly in the project file, promote warnings to compile errors, and pin the latest language version:
<PropertyGroup><Nullable>enable</Nullable><TreatWarningsAsErrors>true</TreatWarningsAsErrors><LangVersion>latest</LangVersion></PropertyGroup>
Without this mechanism, models tend to generate vaguely typed string parameters. Callers cannot tell whether null is accepted, so null-conditional operators end up scattered downstream while null reference exceptions still occur at runtime. Once enabled, Customer? states “may be null” and Customer states “never null.” Suppressing warnings with the null-forgiving operator is strictly forbidden; it only postpones the problem to runtime.
2. Prefer Record Types for Data Carriers
If a type only carries “data + equality + immutable semantics,” use a record type or record struct instead of a mutable class with hand-written equality:
public sealed record OrderDto(Guid Id,Guid CustomerId,decimal Total,IReadOnlyList<OrderLine> Lines);
Models default to mutable classes with hand-written Equals/GetHashCode, and it is easy to forget a new property. The with expression on record types derives new values without mutating the original instance. The distinction matters: entities with identity and behavior, such as aggregate roots, should still be classes, while DTOs, requests and responses, and domain events should prefer record types.
3. Replace Long if/else Chains with switch Expressions
Pattern matching has been a core capability since C# 8, yet many models still write layered type checks. A switch expression is more compact, and the compiler verifies that branches are exhaustive:
public decimal CalculateFee(Payment p) => p switch {{ Method: PaymentMethod.Card, Amount: > 1000m } => p.Amount * 0.015m,{ Method: PaymentMethod.Card } => p.Amount * 0.025m,{ Method: PaymentMethod.BankTransfer } => 0m,_ => throw new ArgumentOutOfRangeException(nameof(p))};
Require the model to supply a fallback branch so that a newly added enum value cannot silently fall into the wrong logic.
2. Async and Concurrency: Prevent Thread Pool Starvation
4. Forbid async void
Except for event handlers, async void cannot be awaited and its exceptions cannot be caught; an exception terminates the process outright. Use async Task uniformly and let the caller decide how to schedule it.
5. Forbid Blocking Access on Async Paths
Reading a task result synchronously blocks the calling thread and quickly exhausts the thread pool under high concurrency, showing up as “random endpoint timeouts.” Always await, and use Task.WhenAll when aggregating multiple async results.
6. Pass Cancellation Tokens Explicitly
Every method that accepts async calls should take a cancellation token parameter and pass it down through each layer, so resources are released promptly when a request times out or a user disconnects.
7. Avoid Unnecessary Thread Switching
Run small, purely computational tasks synchronously. When work genuinely needs to run in the background, use a queue or a background service rather than casually firing off an unawaited task.
3. Dependency Injection and Resource Lifetime
8. Forbid Static Mutable Contexts
Declaring a database context or tracker as a static field causes shared state across requests, corrupted concurrent writes, and accumulating memory. Contexts should be created and disposed per scope, following the “one instance per request” convention.
9. Use Constructor Injection, Reject the Service Locator
Dependencies should be declared explicitly through constructors, which makes them easy to test and replace. Resolving services inside methods hides dependencies and creates implicit coupling.
10. Release Resources Deterministically
Types that implement disposable semantics should be used with a using declaration or declaration expression, ensuring handles, connections, and locks are reclaimed on exception paths as well.
4. Configuration, Exceptions, and Observability
11. Replace String-Indexed Configuration with Strongly Typed Configuration
Reading configuration through string keys everywhere gives no compile-time validation and no help when renaming. Bind configuration to strongly typed objects and validate at startup, so missing values fail at startup rather than on the first request.
12. Reject Broad Exception Catching
A wide block that catches every exception swallows cancellation signals and critical diagnostic information. Catch only expected, handleable exception types, and preserve the original exception context at boundaries; repeated wrapping distorts the stack trace.
13. Require Generated Code to Include Verification
Require the model to produce unit tests and integration tests covering null paths, cancellation paths, and concurrency paths, and state in the constraint file that every new branch must have a corresponding assertion. For observability, logs must be structured and carry a correlation identifier, and metrics and alerts must connect to common monitoring capabilities so problems are caught in pre-production.
Conclusion: Turn Rules into Executable Constraints
The essence of these 13 rules is converting the tacit judgment of senior developers into explicit, machine-readable rules. When the constraint file, the project file, and the test project together form a verifiable guardrail, the quality of AI coding tool output no longer depends on luck. If a team further wires rule validation, static analysis, and automated tests into a cloud container platform and pipeline, and unifies logging and monitoring standards in an environment such as Baidu AI Cloud, it closes the loop from generation to release, so AI genuinely writes maintainable, production-grade code.
