Skip to content

Commit 6da5598

Browse files
authored
Add AV1155: Use the field keyword in auto-properties when additional logic is needed (#316)
1 parent 380f20f commit 6da5598

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

_rules/1155.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
---
2+
rule_id: 1155
3+
rule_category: member-design
4+
title: Use the `field` keyword in auto-properties when additional logic is needed
5+
severity: 3
6+
---
7+
C# 14 introduced the `field` keyword, which provides access to the underlying storage of a property without the need to declare a private field. This eliminates boilerplate while still allowing validation or transformation logic. Furthermore, it protects against other members modifying the underlying value, which breaks encapsulation.
8+
9+
```csharp
10+
// Before C# 14: required a manual backing field
11+
private int maxLength;
12+
public int MaxLength
13+
{
14+
get => maxLength;
15+
set
16+
{
17+
ArgumentOutOfRangeException.ThrowIfLessThan(value, 0);
18+
maxLength = value;
19+
}
20+
}
21+
22+
// With C# 14: use the field keyword
23+
public int MaxLength
24+
{
25+
get;
26+
set
27+
{
28+
ArgumentOutOfRangeException.ThrowIfLessThan(value, 0);
29+
field = value;
30+
}
31+
}
32+
```
33+
34+
Use the `field` keyword when:
35+
- You need getter or setter logic that goes beyond a simple assignment, but don't want to sacrifice the clarity of an auto-property.
36+
- Adding a backing field would add noise without adding meaning.
37+
38+
Don't use `field` when the backing field itself carries meaning (e.g. needs its own name or XML documentation).

0 commit comments

Comments
 (0)