13 Coding Standards for C#/.NET Developers: Make AI Write Professional-Grade Code
When developers ask an AI assistant to "add an endpoint that returns a customer's paginated orders," the generated code may look fine on the surface but hide issues like nullable warnings, async void, .Result blocking, static DbContext, and overly broad exception handling. This article presents 13 C#/.NET coding standards that act as a clear contract for AI-generated code, helping ensure output that is production-ready rather than merely functional in a dev environment.
Introduction
When developers ask an AI assistant to “add an endpoint that returns a customer’s paginated orders,” the generated code may look fine on the surface—but it often hides issues like nullable warnings, async void, .Result blocking, static DbContext, and overly broad exception handling. Such code works well in a development environment, but once it reaches pre-production or high-concurrency scenarios, it can cause deadlocks, memory leaks, or data consistency errors. To elevate an AI assistant from “junior” to “senior engineer,” we need an explicit contract. This article distills 13 coding standards based on C#/.NET best practices to serve as behavioral rules for AI-generated code.
1. Enable Nullable Reference Types and Treat Warnings as Errors
Enforce <Nullable>enable</Nullable> and <TreatWarningsAsErrors>true</TreatWarningsAsErrors> in your .csproj. This ensures every string parameter and return value in AI-generated code carries an explicit nullability annotation. Without it, the AI tends to produce ambiguous parameters like string name that may actually allow null at runtime, forcing downstream code to scatter ?. operators and eventually throwing a NullReferenceException deep in the call stack.
<PropertyGroup><Nullable>enable</Nullable><TreatWarningsAsErrors>true</TreatWarningsAsErrors><LangVersion>latest</LangVersion></PropertyGroup>
Use Customer? to indicate a value that may be null, and Customer for one that is guaranteed non-null. Never use the ! null-forgiving operator to suppress warnings—it only masks the problem, which will resurface at runtime.
2. Use Records for Data Carriers
When a type exists purely to transfer data, events, or value semantics, use record or record struct. The mutable class that AI generates by default requires hand-written Equals/GetHashCode, which are easy to forget when new properties are added. Records automatically provide value-based equality, immutability, and support for with expressions.
public sealed record OrderDto(Guid Id,Guid CustomerId,decimal Total,IReadOnlyList<OrderLine> Lines);
The with expression creates a modified copy without mutating the original. For entities with identity and behavior (such as database aggregate roots), stick with class; but for DTOs, request/response models, and domain events, records are the preferred choice.
3. Prefer Switch Expressions over Long if/else Chains
Pattern matching in C# 8+ offers powerful branching. AI often generates long chains like if (x is Foo f && f.Bar > 0), whereas switch expressions are more concise, more readable, and checked for exhaustiveness by the compiler.
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))};
Property patterns, relational patterns, and positional patterns can significantly reduce branching and nesting while improving maintainability.
4. Enforce Strict Async Rules: No async void and No Blocking Calls
AI frequently generates async void event handlers or synchronous blocking with .Result/.Wait(). These practices make exceptions hard to catch and can cause thread pool starvation or deadlocks. Enforce these rules:
- Async methods should return
TaskorTask<T>;async voidis only acceptable for event handlers. - Never use
.Result,.Wait(), or.GetAwaiter().GetResult()in library code. - Prefer
ConfigureAwait(false)in library scenarios; rely on the synchronization context in UI scenarios. - Use
await usingandawait foreachwhere appropriate.
public async Task<Order> GetOrderAsync(Guid id, CancellationToken ct){var order = await _dbContext.Orders.AsNoTracking().FirstOrDefaultAsync(o => o.Id == id, ct);return order ?? throw new NotFoundException();}
5. Always Use Dependency Injection; Avoid Static Services and Global State
AI may generate static DbContext, static HttpClient, or static configuration access. A static DbContext is not thread-safe, a static HttpClient can suffer from stale DNS, and static configuration makes testing difficult. The correct approach:
- Inject all services through constructors.
- Register lifecycles correctly:
DbContextasScoped,HttpClientviaAddHttpClient(which manages its lifetime). - Avoid the Service Locator pattern unless truly necessary.
public class OrderService{private readonly AppDbContext _db;private readonly IHttpClientFactory _httpFactory;public OrderService(AppDbContext db, IHttpClientFactory httpFactory){_db = db;_httpFactory = httpFactory;}}
6. Handle Exceptions Precisely: Only Catch What You Can Handle
AI often produces try { ... } catch (Exception ex) { }, which swallows system errors. The standards require:
- Catch specific exception types (e.g.,
InvalidOperationException,DbUpdateConcurrencyException). - Re-throw only when wrapping or adding context, using
throw;to preserve the stack trace. - Never leave empty catch blocks; at minimum, log the exception.
- Use methods like
ArgumentNullException.ThrowIfNullfor argument validation.
try{await _db.SaveChangesAsync(ct);}catch (DbUpdateConcurrencyException ex){_logger.LogWarning(ex, "Stale data update attempt");throw new ConflictException("Data has been modified by another user");}
7. Configuration Management: Don’t Use IConfiguration Indexers Everywhere
AI tends to access configuration directly with IConfiguration["SomeKey"] inside business classes, scattering configuration dependencies and hurting testability. The standards:
- Use strongly typed option classes (
IOptions<T>/IOptionsMonitor<T>). - Bind configuration sections in
Startup/Program. - Do not hold
IConfigurationdirectly in constructors, except when registering configuration services.
public class OrderOptions{public int PageSize { get; set; } = 20;public string DefaultCurrency { get; set; } = "CNY";}// Registration: services.Configure<OrderOptions>(configuration.GetSection("Order"));
8. Optimize Data Access: Avoid N+1 Queries and Unindexed Filters
AI may query the database inside loops or forget Include/AsNoTracking. The rules:
- Use
Include/ThenIncludeto load related data, or useSelectprojections to fetch only the fields you need. - Use
AsNoTrackingfor read-only queries. - Avoid database calls inside loops; batch-fetch first.
- When paging with
Skip/Take, always pair them with an explicit ordering.
var orderWithItems = await _db.Orders.Where(o => o.CustomerId == customerId).OrderByDescending(o => o.CreatedAt).Select(o => new OrderSummary(o.Id, o.Total, o.Items.Count)).Skip(page * size).Take(size).ToListAsync(ct);
9. Value Objects and Immutability: readonly struct and init Accessors
Use readonly struct for immutable value types, and init or required accessors for class properties. AI may generate mutable { get; set; } properties that can be unexpectedly modified. Recommended practices:
- Use
recordfor data transfer objects. - Use
private setorinitfor entity properties, and modify state through methods that express intent. - Return
IReadOnlyList<T>orIReadOnlyCollection<T>when exposing collections.
public readonly struct Money{public decimal Amount { get; }public string Currency { get; }public Money(decimal amount, string currency) { Amount = amount; Currency = currency; }}
10. Use Code Analyzers and Static Analysis Tools
Enable <AnalysisLevel>latest</AnalysisLevel> and <EnableNETAnalyzers>true</EnableNETAnalyzers> in your projects, and install common Roslyn analyzers (such as Microsoft.CodeAnalysis.NetAnalyzers). This way, performance, security, and maintainability issues in AI-generated code surface at compile time. Combined with treating warnings as errors, this forces the AI to comply with your standards.
11. Logging: Use Structured Logging, Not String Interpolation
AI often generates _logger.LogInformation($"Order {id} created"), which loses structured information. The standards:
- Use
ILoggerextension methods with message templates, e.g.,LogInformation("Order {OrderId} created", id). - Avoid logging sensitive information.
- Add logging on critical paths (exceptions, boundary conditions), but avoid excessive logging.
_logger.LogInformation("Order {OrderId} processed with {ItemsCount} items", order.Id, order.Items.Count);
12. Concurrency and Thread Safety: Use Task.WhenAll, Don’t Misuse Parallel
AI may use Parallel.For for I/O operations, which exhausts the thread pool. For I/O-bound work, use asynchronous parallelism with Task.WhenAll; reserve Parallel for CPU-bound work, and control the degree of concurrency when you do.
var tasks = orderIds.Select(GetOrderAsync);var orders = await Task.WhenAll(tasks);
Also, avoid lock in asynchronous code—use SemaphoreSlim instead.
13. Explicit Lifecycles and Resource Disposal: Implement IDisposable and IAsyncDisposable
AI may forget to release unmanaged resources. For custom resources, implement IDisposable or IAsyncDisposable following the standard pattern, and use using statements or await using to guarantee cleanup. For HttpClient, manage instances through IHttpClientFactory rather than creating them manually.
public sealed class ResourceHolder : IAsyncDisposable{private readonly SemaphoreSlim _semaphore = new(1,1);public ValueTask DisposeAsync(){_semaphore.Dispose();return ValueTask.CompletedTask;}}
Conclusion
These 13 standards are not scattered tips but a complete “coding contract.” When you add them to your AI assistant’s system prompt or your project’s rules file, the AI’s generated code will automatically follow these principles. The result is fewer defects, better team collaboration, and an AI assistant that truly performs like a senior engineer. Start adding these rules to your projects today and watch your code quality improve.
