Skip to content

Null coalescing assignment C# 8.0code reduction

A short syntax for assigning a value to an object if it is null.

A common pattern in code is to test to see if a variable is null and if it is to assign it some new value.

Prior to C# 8.0 you could either write an if condition (which in many code-formatting rules ends up as 4 lines of code), or use the ? conditional operator with the not-null path assigning it back to itself (an a possible place for a bug to be introduced if the developer doesn't type the right variable again).

C# 8.0 introduces the ?== operator which is more compact and less error-prone way to express this intent.

Code

C#
post ??= LoadPost(postId);
C#
post = post != null ? post : LoadPost(postId);

More information