Showing posts with label Null conditional assignments. Show all posts
Showing posts with label Null conditional assignments. Show all posts

Saturday, 22 November 2025

C# 14 - Null-conditional assignments

What's new in C#

With .NET 10 released in November 2025, new features of C# is available.

Null-conditional assignment

In C# 14, Null-conditional assignment allows using the null-conditional member access operator on the left and side of assignment.

This allows more compact code, but also at the same time allow the code to become a bit more indeterministic since the code will not be run if the object on the left side of the assignment is null.

Consider this simple class :


public class AnotherClass
{
  public ShipmentService ShipmentService = new ShipmentService();
  public Order? CurrentOrder { get; set; }  
  public int? Counter { get; set; } = 0;   
}


public class ShipmentService
{
    public Order? GetCurrentOrder()
    {
        // Simulate fetching the current order, which may return null
        return null; // or return new Order { OrderId = 1234 };
    }
}

public class Order
{
    public int OrderId { get; set; }
}

We do a null check on the instance of <em>AnotherClass</em> ShipmentService here on the left side.


//Demonstrate AnotherClass using null-conditional assignment 
AnotherClass? anotherClass = null;
anotherClass?.CurrentOrder = anotherClass?.ShipmentService.GetCurrentOrder();
Console.WriteLine($"Current order retrieved using null-conditional assignment: {anotherClass?.CurrentOrder?.OrderId} Current order id is NULL? {anotherClass?.CurrentOrder?.OrderId is null}");

It is also possible to use the null check of the null-conditional assignment with compound assignment operators. The compound operators are += and -= . Note that this must be done with member access and cannot be used with values such as integers for example.


//anotherClass still NULL
anotherClass?.Counter += 2;
Console.WriteLine($"anotherClass.Counter = {anotherClass?.Counter}. Is anotherClass.Counter NULL ? {anotherClass?.Counter is null} : outputs NULL since anotherClass is still null");
anotherClass = new AnotherClass();
anotherClass?.Counter -= 15;
Console.WriteLine($"anotherClass.Counter = {anotherClass?.Counter} : outputs -15 since anotherClass is not null"); 
Output of the code above:

Current order retrieved using null-conditional assignment:  Current order id is NULL? True
anotherClass.Counter = . Is anotherClass.Counter NULL ? True : outputs NULL since anotherClass is still null
anotherClass.Counter = -15 : outputs -15 since anotherClass is not null