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 a more compact and less error-prone way to express this intent.

Code

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

Notes

  • Related to the null-coalescing operator C# 2.0 ?? which returns a value if the left side is null but does not assign it
  • Works with nullable value types and reference types
  • The right-hand side is only evaluated if the left-hand side is null

More information