Null-conditional assignment is a new C# 14 feature that simplifies how we assign values to properties or fields of objects that might be null. In this article, I present how to use this feature.
In previous C# versions
C# has hadthe null-conditional operator for a long time (?.), which is useful to avoid NullReferenceException when reading a value. However, we could not use this operator to** assign** a value, which led us to having to write explicit null checks to guard an assignment:
Order? order = GetOrder();
if (order is not null)
{
order.Status = "Processed";
order.UpdatedAt = DateTime.UtcNow;
}Null-conditional assignment in C# 14
Now, in C# 14, we can use the ?. operator on the left side of an assignment, and if the object on the left is null, the assignment is skipped, and no exception is thrown:
Order? order = GetOrder();
order?.Status = "Processed";
order?.UpdatedAt = DateTime.UtcNow;In this example, if the order is null, the assignment to Status and UpdatedAt will not occur, and no NullReferenceException will be thrown. You can also use this feature when dealing with nested objects, for example:
order?.Customer?.Name = "Henrique";
order?.Customer?.ShippingAddress?.City = "Seattle";Conclusion
Null-conditional assignment is a new C# 14 feature that allows you to perform assignments safely on objects that might be null, reducing the need for boilerplate if checks and making your code cleaner, especially when you have multiple optional assignments for an object.
This is the link for the project in GitHub: https://github.com/henriquesd/DotNet10.CSharp14.Demo
If you like this demo, I kindly ask you to give a ⭐️ in the repository.
Thanks for reading!
References