loading experience

C#

C# 14: null-conditional assignment with ?.

The ?. operator now also works on the left of the equals sign: fewer ifs, the same safe behaviour.

C# 14: null-conditional assignment with ?.

For years the ?. operator has let you read a member only if the object is not null. With C# 14 you can also use it to assign: the assignment happens only if the object exists.

If the receiver is null, the right-hand side is not even evaluated.
If the receiver is null, the right-hand side is not even evaluated.

An example

// Before
if (customer is not null)
{
    customer.LastOrder = order;
}

// With C# 14
customer?.LastOrder = order;

If customer is null, the right-hand expression is not evaluated. That is an important detail: if the right side contains an expensive call or one with side effects, it will not run needlessly.

It also works with indexers and compound operators

settings?["theme"] = "dark";
counters?.Total += 1;

Compound assignment operators such as += and -= are allowed; increment and decrement (++ and --) are not.

When to use it

  • To update optional objects, such as a context or a configuration that may be missing.
  • In event handlers and callbacks, where the object may already have been released.

It does not replace good type design: if a value should never be null, declare it non-nullable and let the compiler help you.

Comments (0)

No comments yet.

Leave a comment