Skip to content

Null-conditional assignment C# 14.0readability

Conditionally assign values with `?.` just like reading values.

Null-conditional operators C# 6.0 allowed us to conditionally access members of an object where if the object was null then the result would also be null rather than throwing a NullReferenceException.

C# 14 allows assignment to also now be conditional using the same ?. and ?[] syntax.

Code ​

csharp
var postToDelete = posts.FirstOrDefault(p => p.Id == postId);
postToDelete?.DeletedAt = DateTime.Now;
csharp
var postToDelete = posts.FirstOrDefault(p => p.Id == postId);
if (postToDelete is not null)
{
    postToDelete.DeletedAt = DateTime.Now;
}

Notes ​

  • The right-hand side is only evaluated when the target is not null, so customer?.Order = GetCurrentOrder() does not call GetCurrentOrder for a null customer
  • Works with ?[] and with compound assignment such as += and -=
  • Increment and decrement (++ and --) are not allowed

More information ​

Powered by Intracia