13 C#/.NET Coding Rules for AI-Generated Code
A practical set of 13 coding rules for C#/.NET projects that you can add to a specification file so AI coding tools generate code with explicit nullability, proper async patterns, dependency injection, typed configuration, and structured logging. The article explains why AI-generated code often compiles but fails in pre-production, then walks through the rules by category with configuration snippets and code examples.
Why .NET Needs an AI Coding Specification
In 2026, when you ask an AI coding tool to “add an endpoint that returns paginated orders for a customer,” the output usually compiles. It may still contain parameters with ambiguous nullability semantics, async void methods, threads blocked on .Result, blanket try/catch (Exception) blocks, a static database context, and IConfiguration["..."] string indexing scattered across the codebase. This code runs fine on a developer machine, then produces deadlocks, thread pool starvation, and null reference exceptions once it reaches pre-production.
The root cause is not model capability. It is the absence of a specification file that states the team’s engineering constraints explicitly. The 13 rules below can be written directly into a specification document at the project root and used as hard boundaries for generated code.
Type System and Null Semantics (Rules 1–3)
1. Enable nullable reference types and treat warnings as errors. In the .csproj:
<PropertyGroup><Nullable>enable</Nullable><TreatWarningsAsErrors>true</TreatWarningsAsErrors><LangVersion>latest</LangVersion></PropertyGroup>
Without this, the model generates string parameters with unclear semantics, downstream code is forced to sprinkle ?. everywhere, and null reference exceptions surface at runtime.
2. Express intent through annotations; never use the null-forgiving operator. Customer? means the value may be null; Customer means it never is. The ! operator only suppresses compiler diagnostics, which is self-deception and should be rejected outright during review.
3. Prefer record types for data types. For types defined by “data + equality + immutability,” use record or record struct:
public sealed record OrderDto(Guid Id, Guid CustomerId, decimal Total,IReadOnlyList<OrderLine> Lines);
By default the model generates mutable classes with hand-written Equals/GetHashCode, which easily misses a newly added property. with expressions derive a new instance without mutating the original. Aggregate roots that carry identity and behavior should remain class; transport objects, requests and responses, and domain events should prefer record.
Branching and Flow Control (Rules 4–6)
4. Replace long if/else chains with switch expressions. Pattern matching has been a core C# 8+ feature, yet the model still tends to write if (x is Foo f && f.Bar > 0). Switch expressions are more compact, and the compiler checks whether branch coverage is complete.
5. Prefer the declarative style of pattern matching. Property patterns, relational patterns, and logical patterns express ranges and combined conditions, avoiding the cognitive load of nested checks.
6. Use modern syntax for collection and null checks. Use is null instead of == null, and use the Count/Length properties or pattern checks instead of a pointless Any() enumeration.
Async and Concurrency (Rules 7–9)
7. No async void. Return Task in all cases except event handlers; exceptions cannot be caught and can crash the process.
8. Never block synchronously on async code. .Result and .Wait() occupy threads and can deadlock. The whole call chain should await, passing a CancellationToken where needed.
9. Make the concurrency model explicit. Protect shared state with immutable data or concurrent collections, and avoid the model casually introducing static mutable fields.
Dependency Injection, Configuration, and Data Access (Rules 10–13)
10. Dependencies such as the database context must be injected by the container. A static context causes thread safety problems and connection leaks; lifetime should follow the scope principle.
11. Handle exceptions specifically. Do not wrap catch (Exception) and swallow the exception; catch only expected types and write structured logs.
12. Access configuration in a typed and centralized way. Bind configuration sections with the options pattern instead of filling the screen with IConfiguration["..."] magic strings, and add startup validation.
13. Build in logging and observability. Use structured logging together with general-purpose observability capabilities (logging services, monitoring and alerting, distributed tracing) to correlate request context, making problems easier to locate in container platforms and message queue scenarios.
Putting It into Practice
Once these 13 rules are in the specification file, enforce them with static analysis, unit tests, and a continuous integration pipeline to significantly reduce rework costs. The value of a specification is not slowing down generation, but moving AI coding tool output from “it runs” to “maintainable and ready to ship.”
