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

Code

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

More information