Let the agent move your C# backing fields to the field keyword, and make the compiler catch the three ways it goes wrong
C# 14's field keyword removes hand-written backing fields. The refactor is easy to ask for and easy to get subtly wrong. Pin behaviour first, turn two warnings into errors, and it takes about 15 minutes.

A property with a hand-written backing field is three lines of ceremony around one line of logic. C# 14, which ships with .NET 10, lets you drop the ceremony: the field keyword in an accessor refers to a backing field the compiler writes for you. It’s a mechanical refactor, so it’s a natural job to hand to an agent across a whole codebase.
It’s also a refactor that changes what a name means. Run it carelessly and one of three things happens: a default value disappears, a validation setter gets skipped, or an old member called field quietly rebinds. Each one compiles. Two of them produce a warning that most builds ignore.
Below is a small customer class in C# on .NET 10 with xUnit, the refactor, the three failures with their real output, and a two-line project setting that turns the warnings into errors. The technique works with any coding agent that can read files and run a shell, because the safety net is a test run and a compiler flag, not a tool feature.
The class before
This is the shape the refactor targets: a validating setter, a change-notifying setter and a lazy collection, each with a private field.
public sealed class Customer : INotifyPropertyChanged
{
private string _email = "";
private string? _displayName;
private List<string>? _tags;
public event PropertyChangedEventHandler? PropertyChanged;
public string Email
{
get => _email;
set => _email = value?.Trim().ToLowerInvariant() ?? "";
}
public string? DisplayName
{
get => _displayName;
set
{
if (_displayName == value) return;
_displayName = value;
OnPropertyChanged();
}
}
public List<string> Tags => _tags ??= new List<string>();
private void OnPropertyChanged([CallerMemberName] string? name = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
Pin the behaviour before the refactor
The tests encode what the class does today, including the unglamorous parts: the default value, the null handling, and “raises once per real change”.
public class CustomerTests
{
[Theory]
[InlineData(" Ann@Example.COM ", "ann@example.com")]
[InlineData(null, "")]
[InlineData("", "")]
public void Email_is_trimmed_lowered_and_never_null(string? input, string expected)
{
var c = new Customer { Email = input! };
Assert.Equal(expected, c.Email);
}
[Fact]
public void Email_defaults_to_empty()
{
Assert.Equal("", new Customer().Email);
}
[Fact]
public void DisplayName_raises_once_per_real_change()
{
var c = new Customer();
var raised = new List<string?>();
c.PropertyChanged += (_, e) => raised.Add(e.PropertyName);
c.DisplayName = "Ann";
c.DisplayName = "Ann";
c.DisplayName = null;
Assert.Equal(new[] { "DisplayName", "DisplayName" }, raised);
}
[Fact]
public void Tags_is_created_once_and_kept()
{
var c = new Customer();
c.Tags.Add("vip");
Assert.Same(c.Tags, c.Tags);
Assert.Equal(new[] { "vip" }, c.Tags);
}
}
Run dotnet test and it prints Passed! - Failed: 0, Passed: 6, Skipped: 0, Total: 6. Commit that before any refactor starts, so the agent’s diff is the only thing that changes between a green run and whatever follows.
The prompt
Keep it narrow. An agent given “modernise to C# 14” will touch records, collection expressions and everything else, and the review gets harder.
Refactor only property backing fields to the C# 14 field keyword in Customer.cs.
Rules:
- Remove a private backing field only if the property is its only user.
- If the field had an initialiser, move it to a property initialiser.
- Do not change any other member.
- Run dotnet test and dotnet build after each file and paste the output.
- If a warning mentions 'field', stop and report it instead of fixing it.
The last rule matters. The warnings are the signal, and an agent asked to get the build green will happily silence them.
Failure one: the initialiser that went missing
An easy first pass produces this, in the shape of the documentation’s own examples:
public string Email
{
get;
set => field = value?.Trim().ToLowerInvariant() ?? "";
}
The old private string _email = "" is gone and nothing replaced it. Run the tests:
warning CS9264: Non-nullable property 'Email' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier, or declaring the property as nullable, or safely handling the case where 'field' is null in the 'get' accessor.
Failed Fk.CustomerTests.Email_defaults_to_empty [1 ms]
Expected: ""
Actual: null
Failed! - Failed: 1, Passed: 5, Skipped: 0, Total: 6
A new Customer now returns null from a property typed string. The compiler warned and the test failed, which is two independent signals. Without the test, the warning is the only one, and nullable warnings are the ones teams learn to scroll past. The fix is the initialiser on the property:
public string Email
{
get;
set => field = value?.Trim().ToLowerInvariant() ?? "";
} = "";
Failure two: the initialiser that skips the setter
That fix has a catch, and it isn’t new. A property initialiser writes straight to the backing field and doesn’t run the setter. Take a class that normalises its value:
class Shouty
{
public string Name { get; set => field = value.Trim().ToUpperInvariant(); } = " alice ";
}
Create one and print Name, then assign " bob " and print it again:
initializer bypasses setter: ' alice '
setter applies: 'BOB'
The default keeps its whitespace and its case. A hand-written private string _name = " alice " behaves the same way, so the refactor didn’t change anything, but it moves the behaviour into view where a reviewer can read it. If a default must pass through the validation, set it in a constructor. In the Customer example the default is "", which the setter would leave alone anyway, so the initialiser is safe.
Failure three: an old member called field
This is the one that compiles clean and returns the wrong answer. Some older code names a private member field. In C# 14 the keyword wins inside a property accessor:
class Legacy
{
private int field = 1;
public int Value
{
get => field;
set => field = value;
}
public void Set(int v) => field = v;
}
Call Set(5) and read Value. On the C# 14 compiler it prints Legacy.Value: 0, not 5. Inside Value, field is now the synthesised backing field, and Set still writes the old member. The two have split apart. The compiler says so, with CS9258:
warning CS9258: In language version 14.0, the 'field' keyword binds to a synthesized backing field for the property. To avoid generating a synthesized backing field, and to refer to the existing member, use 'this.field' or '@field' instead.
Microsoft’s C# 14 notes flag this as a potential breaking change and give the same two escapes, @field and this.field, or renaming the member. An agent doing this upgrade across a solution will meet it exactly where a codebase has a member called field,. Renaming the member to something descriptive is the better fix, and it’s a refactor the agent can do under the same tests.
Make the two warnings errors
The prompt tells the agent to stop on these warnings. The project file makes the compiler enforce it, for the agent and for everyone after:
<PropertyGroup>
<WarningsAsErrors>CS9258;CS9264</WarningsAsErrors>
</PropertyGroup>
With that in place the Legacy class stops the build:
error CS9258: In language version 14.0, the 'field' keyword binds to a synthesized backing field for the property. ...
CS9264 is the nullable one from failure one. CS9258 is the rebinding one from failure three. Both warnings stay useful in new code, so leave the setting on after the migration. If the property group already lists other codes, append these to it.
The finished class
The refactored Customer passes all six tests with no warnings:
public string Email
{
get;
set => field = value?.Trim().ToLowerInvariant() ?? "";
} = "";
public string? DisplayName
{
get;
set
{
if (field == value) return;
field = value;
OnPropertyChanged();
}
}
public List<string> Tags => field ??= new List<string>();
Three private fields are gone and the Tags getter is still one line. The change-notification pattern and the lazy initialisation are both in the C# 14 documentation as intended uses.
What it doesn’t change
Lazy initialisation with ??= isn’t thread-safe before or after. If two threads read Tags on first use, each may create a list and one wins. The old _tags ??= ... had the same race, so the refactor neither fixes nor worsens it, but it’s an easy thing for a reviewer to assume the new syntax handles. Use Lazy<T> or a lock when that matters.
The compiler-generated field has a generated name. Reflection on the Shouty type lists <Name>k__BackingField, where a hand-written class lists _name. Code that finds private fields by name, such as a serialiser configured for fields, a test helper that pokes _email, or a mapper that matches a naming convention, can break without a compile error. Search for string literals that look like field names before merging. The tests in the first section won’t find these if they only go through the public property.
Properties that use their field in more than one place still need a real field. Only convert a field when the property is its sole user, which is why the prompt says so.
Try it now
Pick one class with a validating setter. Write the test that pins its default and its null handling, run it green, then paste the prompt above with the file name changed. Add the two warnings to WarningsAsErrors before the agent starts, not after.