New in .NET 10.0 [9]: Null-Conditional Assignment in C# 14.0

Developers can now make an assignment to a property without first checking if the object is null.

listen Print view
Sign with inscription C#

(Image: Pincasso / Shutterstock.com)

1 min. read
By
  • Dr. Holger Schwichtenberg

In addition to the language elements previously listed in this blog series, there is another very helpful new language construct in C# 14.0 that Microsoft calls "Null-Conditional Assignment". This allows developers to make an assignment to a property without first checking if the object is null.

The Dotnet Doctor – Holger Schwichtenberg
Der Dotnet-Doktor – Holger Schwichtenberg

Dr. Holger Schwichtenberg is the technical director of the expert network www.IT-Visions.de, which supports numerous medium-sized and large companies with consulting and training services as well as software development, drawing on the expertise of 53 renowned experts. Thanks to his appearances at numerous national and international conferences, as well as more than 90 specialist books and over 1,500 specialist articles, Holger Schwichtenberg is one of the best-known experts for .NET and web technologies in Germany.

Instead of

if (meineWebsite != null)
{
  meineWebsite.Url = "https://www.IT-Visions.de";
  meineWebsite.Url = meineWebsite.Url.ToLower();
  meineWebsite.Counter += 1;
}

you can now write it more concisely with the question mark before the dot (?.) without if:

meineWebsite?.Url = "https://www.IT-Visions.de";
meineWebsite?.Url = meineWebsite.Url.ToLower();
meineWebsite?.Counter += 1;

This will not cause an error at runtime. However, nothing will happen if the variable myWebsite has the value null.

The variant

meineWebsite?.Owner.Name = "IT-Visions";
Console.WriteLine("Owner: " + meineWebsite?.Owner.Name);

works if Website is null. But not if Website != null and Owner = null. Then you need:

meineWebsite?.Owner?.Name = "IT-Visions";
Console.WriteLine("Owner: " + meineWebsite?.Owner?.Name);

The null-conditional assignment is also allowed with an indexer:

Website[] websites = …;
websites?[0]?.Url = "https://www.IT-Visions.de";

(mma)

Don't miss any news – follow us on Facebook, LinkedIn or Mastodon.

This article was originally published in German. It was translated with technical assistance and editorially reviewed before publication.