Skip to content

Commit 6fc3b6d

Browse files
authored
Add AV1035: Use primary constructors when they improve readability (#313)
1 parent bb03ad5 commit 6fc3b6d

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

_rules/1035.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
---
2+
rule_id: 1035
3+
rule_category: class-design
4+
title: Prefer primary constructors over regular constructors
5+
severity: 3
6+
---
7+
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.
8+
9+
```csharp
10+
// Before primary constructors
11+
public class OrderService
12+
{
13+
private readonly IOrderRepository repository;
14+
15+
public OrderService(IOrderRepository repository)
16+
{
17+
this.repository = repository;
18+
}
19+
}
20+
21+
// With primary constructors
22+
public class OrderService(IOrderRepository repository)
23+
{
24+
public async Task<Order> GetOrderAsync(Guid id)
25+
=> await repository.GetByIdAsync(id);
26+
}
27+
```
28+
29+
Prefer primary constructors when:
30+
- The constructor only captures dependencies or configuration values.
31+
- There is no complex initialization logic that would benefit from a named constructor body.
32+
33+
Avoid primary constructors when:
34+
- The constructor contains parameter validation or non-trivial initialization logic.

0 commit comments

Comments
 (0)