C# style and naming standard¶
This page sets the naming and code style rules for C# in ConnectSoft repositories and in services generated from ConnectSoft templates. It is written for engineers who write or review C# code. The conventions that the code disagreed on are settled in ADR-0105; this page turns them into checkable rules.
The background, the naming patterns of each layer and longer examples are in Naming conventions and Coding standards. How files and types are laid out is in File and type layout. Test method names follow CS-TST-003.
Using var¶
This is guidance, not a rule. Most ConnectSoft code declares locals with var.
- Use
varwhen the type is clear from the right-hand side, for examplenew Order(), a cast or a well-named factory method. - Write the type when the right-hand side does not show it and the type matters to the reader, for example a numeric type or the result of a method whose name does not say what it returns.
Rules¶
CS-NAM-001: Name private fields in camelCase and access them with this.¶
Severity: major · Applies to: service, library, api-client, blazor, template · Enforced by: analyzer SA1101, SA1309 (target: ENF-020) · Status: active
Why¶
One field style across about 16,000 fields keeps code readable when people move between repositories. The this. prefix shows at a glance that a member, not a local, is used. ADR-0105 section 1 records the counts and the decision.
Do¶
- Name private instance fields in camelCase without a prefix, for example
private readonly ILogger logger;. - Access instance fields, properties and methods with
this.. - Name constants and
static readonlyfields in PascalCase, for exampleprivate const int MaxRetries = 3;.
Don't¶
- Prefix fields with
_orm_. - Name constants in
UPPER_CASE.
Example¶
// Do
private readonly IOrderRepository repository;
public OrderService(IOrderRepository repository)
{
this.repository = repository;
}
// Don't
private readonly IOrderRepository _repository;
How to check¶
- Search the change for
private .* _\w+declarations and for field access withoutthis.. - SA1101 and SA1309 report both. The StyleCop configuration is being reconciled under ENF-020.
- Search new
constandstatic readonlydeclarations for names inUPPER_CASE.
CS-NAM-002: Follow the .NET casing and naming conventions for types and members¶
Severity: minor · Applies to: service, library, api-client, blazor, template · Enforced by: analyzer CA1707, CA1715, CA1710 · Status: active
Why¶
The .NET design guidelines are what every C# reader expects. Code that follows them needs no explanation, and analyzers can check it.
Do¶
- Use PascalCase for namespaces, types, methods, properties, events and enum values.
- Use camelCase for parameters and locals.
- Prefix interfaces with
I, for exampleIOrderRepository. - End exception types with
Exception, attribute types withAttributeand options types withOptions. - Use whole words. Accepted abbreviations are
Id,Http,Json,Xml,Api,Uri,Url,Db,UIandIO.
Don't¶
- Use Hungarian notation such as
strNameorintCount. - Use underscores in type or member names.
- Use abbreviations such as
Cust,OrdorMgr.
How to check¶
Read new type and member names. CA1707 reports underscores, CA1715 reports interface and type parameter prefixes, and CA1710 reports missing suffixes.
CS-NAM-003: Name events and commands with their suffix¶
Severity: major · Applies to: service, library, template · Enforced by: manual · Status: retired
Replaced by: CS-MSG-001. Message naming is kept on the messaging page.
CS-NAM-004: Use lowercase, hyphenated, plural paths for new REST contracts¶
Severity: major · Applies to: service, api-client, template · Enforced by: manual · Status: retired
Replaced by: CS-API-001. REST path naming is kept on the API contracts page.
CS-NAM-005: Give asynchronous methods the Async suffix in libraries and API clients¶
Severity: minor · Applies to: library, api-client · Enforced by: analyzer VSTHRD200 · Status: active
Why¶
Callers of a library cannot see its implementation. The suffix tells them that a method must be awaited and that a synchronous twin may exist. Service code is generated differently: controller actions, service contract operations and domain processors are named after the operation, and the service templates turn VSTHRD200 off for that reason.
Do¶
- In libraries and API clients, end every method that returns
Task,Task<T>,ValueTaskorValueTask<T>withAsync, for exampleGetOrderAsync.
Don't¶
- Add
Asyncto members that are exempt, because the templates generate them without it: - controller actions;
- gRPC and other service contract operations;
- methods of domain
Processor,RetrieverandUseCaseinterfaces and their implementations. - Drop the suffix from a public library method.
Example¶
// Library or API client
public Task<Order> GetOrderAsync(Guid orderId, CancellationToken token);
// Service domain processor, as generated by the template
Task<IOrder> CreateOrder(CreateOrderInput input, CancellationToken token = default);
How to check¶
- In library and API client repositories, VSTHRD200 reports a missing suffix.
- In service repositories, check only types that are not exempt, such as infrastructure helpers and service agents.
CS-STY-001: Use a block-scoped namespace with the usings inside it¶
Severity: minor · Applies to: service, library, api-client, blazor, template · Enforced by: analyzer SA1200 (target: ENF-020) · Status: active
Why¶
Almost every ConnectSoft file uses this layout. Mixing styles makes diffs noisy and confuses code generators. ADR-0105 section 2 records the decision.
Do¶
- Declare the namespace with a block, and put the
usingdirectives inside it.
Don't¶
- Use a file-scoped namespace (
namespace Orders;). - Put
usingdirectives above the namespace. - Convert existing files only to change the style. The repositories that use the other style are listed under ENF-016.
Example¶
namespace ConnectSoft.Orders.DomainModel
{
using System;
using System.Threading.Tasks;
public sealed class OrderTotals
{
}
}
How to check¶
SA1200 reports usings outside the namespace once usingDirectivesPlacement is insideNamespace. Search new files for ^namespace .*;.
CS-STY-002: Write methods and properties with block bodies¶
Severity: nit · Applies to: service, library, api-client, blazor, template · Enforced by: manual (target: ENF-001) · Status: active
Why¶
One body style makes members look the same, makes it easy to add a log line or a guard later, and keeps breakpoints and coverage lines predictable.
Do¶
- Write methods, properties, indexers and accessors with a
{ }block body. - Keep lambdas as they are; this rule covers members only.
Don't¶
- Use
=>expression bodies for methods or properties in new code.
Example¶
// Do
public decimal Total
{
get
{
return this.lines.Sum(line => line.Amount);
}
}
// Don't
public decimal Total => this.lines.Sum(line => line.Amount);
How to check¶
- Search new members for
) =>and for property declarations followed by=>. - The
.editorconfigoptionscsharp_style_expression_bodied_methodsandcsharp_style_expression_bodied_propertiescan report this once the template.editorconfigis repaired (ENF-001).
CS-STY-003: Capture primary constructor parameters in readonly fields¶
Severity: minor · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
Primary constructors are allowed, because they remove constructor boilerplate. A parameter used directly in a member body, however, is a hidden mutable field that does not follow CS-NAM-001 and cannot be told apart from a local.
Do¶
- Assign each primary constructor parameter to a
private readonlyfield of the same name. - Use the field with
this.in member bodies.
Don't¶
- Use a primary constructor parameter inside a method, property or lambda.
Example¶
public sealed class CreateOrderUseCase(
ILogger<CreateOrderUseCase> logger,
IOrderRepository repository)
: ICreateOrderUseCase
{
private readonly ILogger<CreateOrderUseCase> logger = logger;
private readonly IOrderRepository repository = repository;
public async Task<Order> Execute(CreateOrderInput input, CancellationToken token)
{
return await this.repository.InsertAsync(input.ToOrder(), token).ConfigureAwait(false);
}
}
How to check¶
In a class with a primary constructor, every parameter appears once, in a field initializer. The compiler warning CS9124 reports a parameter that is both captured and used to initialize a field.
CS-STY-004: Seal classes that are not designed for inheritance¶
Severity: minor · Applies to: service, library, api-client, blazor, template · Enforced by: analyzer CA1852 · Status: active
Why¶
A sealed class states that it has no extension points, so it can be changed without breaking unknown subclasses. It also lets the runtime devirtualize calls.
Do¶
- Declare new classes
sealedunless they are designed as a base class. - Make a class designed for inheritance
abstract, or document its extension points.
Don't¶
- Leave a new concrete class unsealed by default.
- Seal or unseal existing classes only to follow this rule. In a library, sealing a public class is a breaking change.
Example¶
How to check¶
- CA1852 reports internal classes that could be sealed.
- For new public classes, check that
sealedis present or that the class is meant to be inherited.
CS-STY-005: Keep wire contracts as classes, not records¶
Severity: minor · Applies to: service, library, api-client, template · Enforced by: manual · Status: active
Why¶
Requests, responses, DTOs and message contracts pass through serializers, mappers and persistence mappings that all expect a class with settable or init-only properties. Records add value equality, a with copy and a positional constructor that these tools handle differently. Keeping contracts as classes keeps their behaviour the same across REST, gRPC, messaging and mapping.
Do¶
- Declare ServiceModel and MessagingModel contracts and DTOs as classes with
{ get; set; }or{ get; init; }properties. - Use a record for an internal immutable value that is never serialized as a contract, for example a cache key or an intermediate result.
Don't¶
- Declare a request, response, DTO, event or command as a
record.
Example¶
// Contract
public class CreateOrderRequest
{
public Guid CustomerId { get; set; }
}
// Internal value
internal sealed record OrderCacheKey(Guid TenantId, Guid OrderId);
How to check¶
Search new files in ServiceModel, MessagingModel and contract projects for record.