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.
(Image: Pincasso / Shutterstock.com)
- 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.
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)