C# 14: Null Conditional Assignment
C Sharp .NET

C# 14: Null Conditional Assignment

Mishel Shaji
Mishel Shaji

C# 14 introduces a highly anticipated quality-of-life feature that makes handling potentially null objects cleaner than ever: Null-Conditional Assignment.

You can now use the null-conditional operators (?. and ?[]) directly on the left-hand side of an assignment operation.

The Problem: What It Solves

Historically, you could use the ?. operator it to safely read data from a potentially null object, but you couldn't use it to write data. If you wanted to assign a value to a property, you were forced to write manual null checks to prevent a NullReferenceException.

C# 14 removes this limitation. Now, if the object on the left side of the assignment is null, the entire line safely short-circuits (skips execution) instead of crashing your application.

Clean Code: Before vs. After

Let's look at a practical example. Imagine an application where you want to update a user's address, but the Customer object might be null.

❌ The Old Way (Pre-C# 14)

To safely assign a value, you had to wrap your logic in an explicit if statement or use a verbose pattern-matching guard.

Customer? customer = GetCustomerData();

// Manual check required before assigning a value
if (customer != null)
{
    customer.City = "Seattle";
}

The New Way (C# 14)

Now, you can compress that entire operation into a single, elegant line. The assignment only fires if customer is an active object.

Customer? customer = GetCustomerData();

// Fast, readable, and perfectly safe
customer?.City = "Seattle";

Working with Collections (?[])

This feature is equally powerful when working with indexers, arrays, or dictionaries that might not be initialized yet.

Instead of writing a full null-check block for a configuration dictionary, you can use ?[] on the left-hand side:

Dictionary<string, string>? settings = LoadConfig();

// If settings is null, this line is safely ignored
settings?["Theme"] = "Dark";

Key Benefits

  • Goodbye Boilerplate: Eliminates repetitive if (obj != null) blocks that clutter your methods.
  • Better Readability: Keeps your code concise, making the core business logic much easier to scan.
  • Syntax Symmetry: The ?. operator now behaves consistently whether you are fetching a value or setting one.