C# Coding Standards
Enterprise-level C# standards for teams building production services on .NET. These rules apply to all service code, libraries, background workers, and API projects.
Naming Conventions
Clear, consistent naming is the first defence against misunderstanding.
Classes and interfaces
// Classes use PascalCase
public class OrderProcessor { }
public class PaymentGateway { }
// Interfaces are prefixed with I
public interface IOrderRepository { }
public interface IPaymentProvider { }
Methods and properties
// Methods use PascalCase and start with a verb
public async Task<Order> GetOrderByIdAsync(Guid orderId) { }
public void ValidatePayload(CreateOrderRequest request) { }
// Properties use PascalCase
public string CustomerId { get; init; }
public decimal TotalAmount { get; private set; }
Local variables and parameters
// Local variables and parameters use camelCase
var customerId = Guid.NewGuid();
var totalAmount = CalculateTotal(lineItems);
Private fields
// Private fields are prefixed with underscore
private readonly ILogger<OrderProcessor> _logger;
private readonly IOrderRepository _orderRepository;
Constants and static readonly
// Constants use SCREAMING_SNAKE_CASE or PascalCase
private const int MaxRetryAttempts = 3;
private const string DefaultCurrency = "GBP";
// Static readonly fields use PascalCase
private static readonly TimeSpan CacheExpiry = TimeSpan.FromMinutes(5);
Folder and Project Structure
A well-structured solution separates concerns and makes navigation predictable.
src/
Acme.Orders.Api/
Controllers/
OrdersController.cs
Middleware/
ExceptionHandlingMiddleware.cs
Program.cs
appsettings.json
appsettings.Production.json
Acme.Orders.Application/
Commands/
CreateOrder/
CreateOrderCommand.cs
CreateOrderCommandHandler.cs
CreateOrderCommandValidator.cs
Queries/
GetOrderById/
GetOrderByIdQuery.cs
GetOrderByIdQueryHandler.cs
Contracts/
IOrderRepository.cs
IPaymentProvider.cs
Exceptions/
OrderNotFoundException.cs
Acme.Orders.Domain/
Entities/
Order.cs
OrderLine.cs
ValueObjects/
Money.cs
CustomerId.cs
Events/
OrderCreatedEvent.cs
Acme.Orders.Infrastructure/
Persistence/
OrdersDbContext.cs
Repositories/
OrderRepository.cs
ExternalServices/
PaymentProviderClient.cs
Migrations/
tests/
Acme.Orders.UnitTests/
Acme.Orders.IntegrationTests/
Rule of thumb:
- each project has one responsibility
- the Application layer owns contracts and orchestration
- the Domain layer has no dependencies
- the Infrastructure layer depends on Application contracts, not the other way
Error Handling
Errors should be explicit, logged, and handled consistently.
// Use custom exceptions for domain errors
public sealed class OrderNotFoundException : Exception
{
public OrderNotFoundException(Guid orderId)
: base($"Order {orderId} was not found.") { }
}
// Throw early, handle at the boundary
public async Task<OrderDto> GetOrderByIdAsync(Guid orderId)
{
var order = await _orderRepository.FindAsync(orderId)
?? throw new OrderNotFoundException(orderId);
return _mapper.Map<OrderDto>(order);
}
Never swallow exceptions silently:
// Avoid this
try
{
await ProcessAsync();
}
catch (Exception)
{
// nothing here - this hides real problems
}
// Prefer this
try
{
await ProcessAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to process order {OrderId}", orderId);
throw;
}
Async and Await
All I/O operations should be async throughout the call chain.
// Always propagate async - never block on async code
public async Task<IReadOnlyList<OrderDto>> GetActiveOrdersAsync(
CancellationToken cancellationToken = default)
{
return await _orderRepository
.GetActiveAsync(cancellationToken);
}
// Pass cancellation tokens from API boundary to data layer
public async Task<IActionResult> GetOrder(
Guid id,
CancellationToken cancellationToken)
{
var result = await _queries.GetOrderByIdAsync(id, cancellationToken);
return Ok(result);
}
Common anti-patterns to avoid:
.Resultand.Wait()on async methodsasync voidexcept in event handlers- fire-and-forget without error handling
Dependency Injection
Register and resolve dependencies through interfaces, not concrete types.
// Registration in Program.cs or a dedicated extension method
services.AddScoped<IOrderRepository, OrderRepository>();
services.AddScoped<IPaymentProvider, StripePaymentProvider>();
services.AddSingleton<IDateTimeProvider, SystemDateTimeProvider>();
// Constructor injection only - no service locator pattern
public class OrderProcessor
{
private readonly IOrderRepository _orderRepository;
private readonly ILogger<OrderProcessor> _logger;
public OrderProcessor(
IOrderRepository orderRepository,
ILogger<OrderProcessor> logger)
{
_orderRepository = orderRepository;
_logger = logger;
}
}
Logging
Use structured logging with meaningful context in every log entry.
// Log the event and relevant identifiers
_logger.LogInformation(
"Order {OrderId} created for customer {CustomerId}",
order.Id, order.CustomerId);
_logger.LogWarning(
"Payment provider returned retry signal for order {OrderId}",
order.Id);
_logger.LogError(ex,
"Unexpected failure while processing order {OrderId}",
order.Id);
Logging levels:
- Debug: detailed technical trace, not for production by default
- Information: normal application events
- Warning: recoverable issues or unexpected states
- Error: failures that need attention
- Critical: system-level failures requiring immediate action
Null Safety
Use nullable reference types and handle null defensively at boundaries.
// Enable nullable in csproj
// <Nullable>enable</Nullable>
// Return null-safe results using patterns from the domain
public async Task<Order?> FindAsync(Guid orderId) { }
// Use null-coalescing throw for guard logic
var order = await _repo.FindAsync(id)
?? throw new OrderNotFoundException(id);
Testing Expectations
Unit tests use a clear Arrange-Act-Assert structure.
[Fact]
public async Task CreateOrder_WithValidRequest_ReturnsOrderId()
{
// Arrange
var request = new CreateOrderRequest
{
CustomerId = Guid.NewGuid(),
Items = [new OrderItem("SKU001", 2)]
};
_repositoryMock
.Setup(r => r.SaveAsync(It.IsAny<Order>(), default))
.Returns(Task.CompletedTask);
// Act
var result = await _handler.Handle(request, default);
// Assert
result.OrderId.Should().NotBeEmpty();
}
Common Pitfalls
- mixing business logic into controllers
- catching
Exceptionwithout re-throwing - using static state or
HttpContextoutside middleware - not testing the unhappy path
- ignoring cancellation tokens in long-running operations
Key Takeaways
- naming should communicate intent without needing comments
- project structure should mirror the architecture
- async goes all the way down
- errors are explicit and logged with context
- production code is tested, injected, and logged consistently