> ## Content Index
> Fetch the complete content index at: https://mishelshaji.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# C# 14: Null Conditional Assignment
- URL: https://mishelshaji.com/c-sharp-14-null-conditional-assignment/
- Published: 2026-05-18T06:15:30.000Z
- Updated: 2026-05-18T06:15:30.000Z
- Description: When working with numerical data in C#, you frequently need to choose the right data type to represent non-integer values. C# supports three basic floating-point types: float, double, and decimal.
- Author: Mishel Shaji
- Tags: C Sharp, .NET

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.

```csharp
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.

```csharp
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:

```csharp
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.