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.
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.