The field keyword and null-conditional assignment

suggest change

C# 14 (.NET 10) removes two common bits of boilerplate:

The last section is a short tour of the smaller C# 14 additions: nameof with unbound generic types, lambda parameter modifiers without types, partial constructors and events, and user-defined compound assignment operators.

The examples are .NET 10 / C# 14 file-based programs: save the code as app.cs and run it with dotnet run app.cs. All output comes from real runs.

The field keyword

The problem

An auto-property is one line:

public string Name { get; set; }

But the moment you need to do anything in the setter, even trim a string, you have to write a full property with a separate field. The book's Initializing Property with a Backing Field article shows that classic form:

private string _name = "";

public string Name
{
    get { return _name; }
    set { _name = value.Trim(); }
}

Now the class has two members for one value, and the rest of the class can read and write _name directly, skipping the trimming.

field in an accessor

In C# 14, field inside a property accessor refers to the backing field the compiler creates for that property. You write only the accessor that needs logic and keep the other one as plain get; or set;:

var p = new Product();
p.Name = "  Coffee beans  ";
p.Price = 12.5m;
Console.WriteLine($"[{p.Name}] {p.Price}");

try
{
    p.Price = -1;
}
catch (ArgumentOutOfRangeException e)
{
    Console.WriteLine(e.Message);
}

class Product
{
    public string Name
    {
        get;
        set => field = value.Trim();
    } = "";

    public decimal Price
    {
        get;
        set
        {
            ArgumentOutOfRangeException.ThrowIfNegative(value);
            field = value;
        }
    }
}
[Coffee beans] 12.5
value ('-1') must be a non-negative value. (Parameter 'value')
Actual value was -1.

Notes:

These are sometimes called semi-auto properties or field-backed properties. The compiler generates the same kind of hidden field as for an auto-property:

using System.Reflection;

var t = new Temperature { Celsius = 21.537 };
Console.WriteLine(t.Celsius);

foreach (var f in typeof(Temperature).GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
    Console.WriteLine(f.Name);

class Temperature
{
    public double Celsius
    {
        get;
        set => field = Math.Round(value, 1);
    }
}
21.5
<Celsius>k__BackingField

A property gets a backing field if any accessor is get;/set;/init; or uses field. If both accessors have bodies and neither uses field, there's no backing field, as before.

field is only valid inside accessors

field is a contextual keyword that only exists inside a property accessor. A method of the same class can't reach the backing field:

class Report
{
    public string Summary => field ??= "x";

    public void Invalidate() => field = null;
}
error CS0103: The name 'field' does not exist in the current context

If other members need to change the value, give the property a setter, private if needed, and go through it.

Lazy initialization

field ??= ... in a getter computes a value on first access and caches it:

var r = new Report();
Console.WriteLine("created");
Console.WriteLine(r.Summary);
Console.WriteLine(r.Summary);
r.Invalidate();
Console.WriteLine(r.Summary);

class Report
{
    private int _builds;

    public string Summary
    {
        get => field ??= Build();
        private set;
    }

    public void Invalidate() => Summary = null!;

    private string Build()
    {
        _builds++;
        Console.WriteLine($"building (#{_builds})");
        return $"summary v{_builds}";
    }
}
created
building (#1)
summary v1
summary v1
building (#2)
summary v2

The property type is non-nullable string because the getter never returns null. Invalidate resets the cache through the private setter; the null! tells the compiler that storing null there is deliberate (the Nullable reference types article explains !).

This is not thread-safe: two threads can both see null and both call Build. For a cache shared between threads use Lazy<T> or LazyInitializer.EnsureInitialized. The older pattern without field is shown in Lazy properties initialization with null coalescing operator.

INotifyPropertyChanged

Change notification is where field saves the most code. Each property used to need its own private field. Now the property passes ref field to a helper:

using System.ComponentModel;
using System.Runtime.CompilerServices;

var vm = new PersonViewModel();
vm.PropertyChanged += (_, e) => Console.WriteLine($"changed: {e.PropertyName}");

vm.FirstName = "Ada";
vm.FirstName = "Ada";      // same value: no event
vm.Age = 36;

class PersonViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    public string FirstName
    {
        get;
        set => SetField(ref field, value);
    } = "";

    public int Age
    {
        get;
        set => SetField(ref field, value);
    }

    private void SetField<T>(ref T storage, T value, [CallerMemberName] string name = "")
    {
        if (EqualityComparer<T>.Default.Equals(storage, value))
            return;
        storage = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}
changed: FirstName
changed: Age

Compare with INotifyPropertyChanged With Generic Set Method, which needs a field per property.

field with init and required

field works in init accessors too, so an immutable property can normalize its value. It combines with required (see init-only setters and required members):

var u = new User { Email = "  Ada@Example.COM " };
Console.WriteLine(u.Email);
Console.WriteLine(u.Nickname);

class User
{
    public required string Email
    {
        get;
        init => field = value.Trim().ToLowerInvariant();
    }

    // getter handles null, so no CS9264 warning
    public string Nickname
    {
        get => field ?? "(none)";
        set;
    }
}
ada@example.com
(none)

Nullable warnings

With nullable reference types enabled, a non-nullable field-backed property gets a warning if nothing sets it:

class Temperature
{
    public string Name { get; set => field = value.Trim(); }
}
warning CS9264: Non-nullable property 'Name' 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.

The message lists the fixes: add an initializer (= "";), mark the property required, make it string?, or make the getter handle null as Nickname and Summary do above. The compiler looks at the getter: if get copes with a null field (as field ?? "(none)" and field ??= Build() do), it treats the backing field as nullable and doesn't warn.

The name conflict gotcha

Before C# 14, field was an ordinary identifier, so some classes have a member called field. Inside a property accessor, field now means the backing field, not that member. The compiler warns about it:

var s = new Sensor();
s.Value = 5;
Console.WriteLine(s.Value);
Console.WriteLine(s.Describe());

class Sensor
{
    private int field = 100;

    public int Value
    {
        get => field;
        set => field = value;
    }

    public string Describe() => $"member 'field' = {field}";
}
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.
5
member 'field' = 100

The code compiles, but it silently changed meaning: Value now reads and writes its own hidden field, and the member field stays at 100. Code that worked under C# 13 behaves differently after upgrading to .NET 10.

Fix it in one of two ways:

The same applies to a local variable or parameter named field used inside an accessor. Outside accessors, as in Describe, field is still an ordinary name.

Treat CS9258 as an error when upgrading old code.

Null-conditional assignment

Assigning through ?.

?. and ?[] have been available for reading since C# 6 (see Null-conditional Operators and Null propagation). Assignment needed an explicit check:

if (customer is not null)
{
    customer.Email = Normalize(input);
}

C# 14 allows a null-conditional access as the target of an assignment:

Customer? found = Find("ada");
Customer? missing = Find("bob");

found?.Email = Normalize("  ADA@EXAMPLE.COM ");
missing?.Email = Normalize("  BOB@EXAMPLE.COM ");

Console.WriteLine(found?.Email ?? "(null)");
Console.WriteLine(missing?.Email ?? "(null)");

static Customer? Find(string name) => name == "ada" ? new Customer() : null;

static string Normalize(string s)
{
    Console.WriteLine($"Normalize(\"{s}\")");
    return s.Trim().ToLowerInvariant();
}

class Customer
{
    public string? Email { get; set; }
}
Normalize("  ADA@EXAMPLE.COM ")
ada@example.com
(null)

Notice that Normalize ran only once. The right-hand side is evaluated only if the left side isn't null, exactly like the if version. Don't put side effects on the right side that must always happen.

Compound assignment and indexers

All compound assignment operators work: +=, -=, *=, ??= and the rest, with ?. member access and ?[] element access:

var real = new Stats();
Stats? stats = real;
Stats? none = null;

stats?.Hits += 1;
stats?.Hits += 1;
none?.Hits += 1;              // nothing happens

stats?.Counts[2] = 10;
stats?.Counts[2] *= 3;
stats?.Tags ??= ["new"];
none?.Tags ??= ["never"];

Console.WriteLine($"{real.Hits} {real.Counts[2]} {string.Join(",", real.Tags!)}");

int[] numbers = [1, 2, 3];
int[]? maybeNumbers = numbers;
maybeNumbers?[0] = 100;
Console.WriteLine(string.Join(",", numbers));

class Stats
{
    public int Hits { get; set; }
    public int[] Counts { get; } = new int[4];
    public List<string>? Tags { get; set; }
}
2 30 new
100,2,3

stats?.Counts[2] = 10 checks only stats. If Counts itself could be null you'd write stats?.Counts?[2] = 10.

Chains and the value of the expression

In a chain, the assignment is skipped if any ?. link is null. The whole expression has a value too: the assigned value, or null if the assignment was skipped. For a value type its type is nullable (int?):

var c = new Customer();
Order? order = new Order { Customer = c };
Order? noCustomer = new Order();

order?.Customer?.Address = "1 Main St";
noCustomer?.Customer?.Address = "2 Side St";   // Customer is null: skipped

Console.WriteLine(c.Address);

Stats? none = null;
Stats? some = new Stats();

int? r1 = none?.Hits = 5;
int? r2 = some?.Hits = 5;
Console.WriteLine(r1 is null ? "null" : r1.ToString());
Console.WriteLine(r2);

class Order { public Customer? Customer { get; set; } }
class Customer { public string? Address { get; set; } }
class Stats { public int Hits { get; set; } }
1 Main St
null
5

Using the result like this is legal but hard to read; normally null-conditional assignment is written as a statement.

Events

+= and -= on events work the same way, which is handy when subscribing to an optional component:

Button? ok = new Button();
Button? cancel = null;

ok?.Clicked += () => Console.WriteLine("ok clicked");
cancel?.Clicked += () => Console.WriteLine("never attached");

ok?.Click();

class Button
{
    public event Action? Clicked;
    public void Click() => Clicked?.Invoke();
}
ok clicked

What isn't allowed

Increment and decrement are not supported:

Stats? stats = new Stats();
stats?.Hits++;

class Stats { public int Hits { get; set; } }
error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer

Use stats?.Hits += 1 instead.

A gotcha with nullable flow analysis: after x?.Prop = ... the compiler considers x possibly null, even if it was non-null before, because the ?. is treated as a null test. If you know the value isn't null, plain x.Prop = ... is clearer anyway; use ?. only for references that really can be null.

Other C# 14 additions

C# 14 also brings extension members (extension blocks that add properties, operators and static members to existing types), covered in its own article, and implicit conversions from arrays to Span<T>/ReadOnlySpan<T>. The remaining small features:

nameof with unbound generic types

nameof now accepts an open generic type like List<>. Before, you had to pick an arbitrary type argument: nameof(List<int>).

Console.WriteLine(nameof(List<>));
Console.WriteLine(nameof(Dictionary<,>));
Console.WriteLine(nameof(List<>.Count));
List
Dictionary
Count

See nameof Operator for the basics.

Lambda parameter modifiers without types

Lambda parameters with out, ref, in or scoped used to require explicit types for every parameter: (string text, out int result) => .... Now the types are inferred from the delegate:

TryParse<int> parse = (text, out result) => int.TryParse(text, out result);

if (parse("42", out var n))
    Console.WriteLine(n + 1);

Scale scale = (ref value, factor) => value *= factor;
double d = 1.5;
scale(ref d, 4);
Console.WriteLine(d);

delegate bool TryParse<T>(string text, out T result);
delegate void Scale(ref double value, double factor);
43
6

params still requires an explicit type.

Partial constructors and partial events

C# 13 allowed partial properties and indexers. C# 14 adds instance constructors and events. One part declares the member, the other implements it. This exists mainly for source generators: you write the declaration and a generator writes the body.

var w = new Widget("gear");
w.Changed += () => Console.WriteLine("handler called");
w.Raise();

// Normally the declaring half is in your file and the
// implementing half is written by a source generator.
partial class Widget
{
    public partial Widget(string name);
    public partial event Action? Changed;
}

partial class Widget
{
    private Action? _changed;
    public string Name { get; }

    public partial Widget(string name)
    {
        Name = name;
        Console.WriteLine($"created {name}");
    }

    public partial event Action? Changed
    {
        add { Console.WriteLine("subscribe"); _changed += value; }
        remove { _changed -= value; }
    }

    public void Raise() => _changed?.Invoke();
}
created gear
subscribe
handler called

The implementing event part must have add and remove accessors. Only the implementing constructor can have a : this(...) or : base(...) initializer.

User-defined compound assignment operators

Until now a += b on a user type always meant a = a + b: call operator +, which builds a new object, and reassign. C# 14 lets a type define += (and -=, *=, etc., plus ++/--) directly as an instance method that mutates the object in place. That avoids allocating a copy for big mutable types such as buffers or matrices:

var m = new Money(10m);
var alias = m;
m += 5m;
Console.WriteLine($"{m.Amount} {alias.Amount} {ReferenceEquals(m, alias)}");

class Money(decimal amount)
{
    public decimal Amount { get; private set; } = amount;

    // classic operator: returns a new object
    public static Money operator +(Money a, decimal b) => new(a.Amount + b);

    // C# 14: compound assignment, mutates in place
    public void operator +=(decimal b) => Amount += b;
}
15 15 True

m was modified in place, so alias, which refers to the same object, sees 15 too. Without the operator += definition, m += 5m would call operator +, m would point to a new object, and alias.Amount would still be 10. The operator is public, non-static, returns void and takes one parameter. If a type defines only +, compound assignment keeps working the old way. See Overloadable operators for ordinary operator overloading.

Summary

Feature Example Replaces
field keyword set => field = value.Trim(); a private field plus a full property
lazy getter get => field ??= Load(); a nullable private field
null-conditional assignment customer?.Email = x; if (customer is not null) customer.Email = x;
null-conditional compound assignment stats?.Counts[i] += 1; an if around the update
nameof unbound generic nameof(List<>) nameof(List<int>)
lambda modifiers without types (text, out result) => ... (string text, out int result) => ...
partial constructors and events public partial Widget(string name); generator-specific workarounds
compound assignment operators public void operator +=(T x) allocate a new object on each +=

All of these need C# 14, which is the default language version when targeting .NET 10.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents