Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions _rules/1035.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
---
rule_id: 1035
rule_category: class-design
title: Use primary constructors when they improve readability
Comment thread
dennisdoomen marked this conversation as resolved.
Outdated
severity: 3
---
C# 12 introduced primary constructors, which let you declare constructor parameters directly on the class or record declaration. This reduces boilerplate when the constructor mainly exists to assign dependencies to fields or auto-properties.

```csharp
// Before primary constructors
public class OrderService
{
private readonly IOrderRepository repository;

public OrderService(IOrderRepository repository)
{
this.repository = repository;
}
}

// With primary constructors
public class OrderService(IOrderRepository repository)
{
public async Task<Order> GetOrderAsync(Guid id)
=> await repository.GetByIdAsync(id);
}
```

Prefer primary constructors when:
- The constructor only captures dependencies or configuration values.
- There is no complex initialization logic that would benefit from a named constructor body.

Avoid primary constructors when:
Comment thread
dennisdoomen marked this conversation as resolved.
- The constructor contains validation or non-trivial initialization logic.
- The parameter names would be confused with members (the parameter is in scope throughout the entire class body).
Comment thread
dennisdoomen marked this conversation as resolved.
Outdated