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 callGetCurrentOrderfor a nullcustomer - Works with
?[]and with compound assignment such as+=and-= - Increment and decrement (
++and--) are not allowed