C#  

Null Conditional Assignment in C#

You may already know null conditional access (?.), which safely calls members on possibly null objects.

Before the new C #14 update, we could only call it on the right side of an assignment, which means this way:

using System;
public class Person {
    public string Name {get;set;}
}
public class HelloWorld
{
    public static void Main(string[] args)
    {
        string name = person?.FirstName;
        Console.WriteLine(name);
    }
} 

This will perfectly work, but calling person?.FirstName = "Person" won't be possible, we will get

public class HelloWorld
{
    public static void Main(string[] args)
    {
        Person? p = new Person();
        p?.Name = "John";
        Console.WriteLine (p.Name);
    }
}

error CS0131: The left-hand side of an assignment must be a variable, property or indexer

In this article, you'll learn:

  • What ?. actually does

  • What's new in C# 14

The Null-Conditional Access Operator (?.)

This operator allows you to safely call a member when the object might be null.

Before ?.

Person? p = GetPerson();
if (p != null)
{
    Console.WriteLine(p.Address?.City);
}

After ?.

Person? p = GetPerson();
Console.WriteLine(p?.Address?.City);

If p or address is null, then the result is null, no exception is thrown.

The New C# 14 Feature: Null Conditional Assignment (?.=)

C# 14 introduces null conditional assignment, letting you assign a value only if the left side is not null:

Syntax

objectVariable?.= value;

What it means

Assign to this member only if the object isn't null.

Example

Person? p = GetPerson();
p?.Name = "John";   // invalid before C#14  
                    // valid in C#14 thanks to "?.="  

Real C#14 example

Person? person = GetPerson();

person?.= new Person
{
    Name = "John",
    Age = 30
};

If person is null => assignment is skipped.
If not null => the assignment executes normally.

Important Notes and Limitations

Not all assignments can use (?.=),C# still disallows ambiguous cases.It does NOT "initialize if null"

This is NOT allowed:

person?.= new Person(); // DOES NOT replace "??="

If you want to initialize when null:

person ??= new Person();

To resume

OperatorMeaning
?.Access member if not null
?.=Assign member if not null
??=Assign left side only if null