C# 8 - Null coalescing/compound assignment

There are a lot of cool new features in C# 8 and one of my favorites is the new Null coalescing assignment operator.

Stefán Jökull Sigurðarson

Stefán Jökull Sigurðarson

Hi friends.

There are a lot of cool new features in C# 8 and one of my favorites is the new Null coalescing assignment (or compound assignment, whichever you prefer) operator. If you have ever written code like this:

You can simplify this code A LOT!

That is the new ??= operator in action, which takes care of doing the null check and assignment for you in one sweet syntactic sugar-rush! I also find it more readable, but some people might disagree, and that fine. Just pick whatever you prefer :)

And the best part is that it actually compiles down to the same efficient code! Just take a look at this sharplab.io sample to see what I mean.

You might have solved this with a Lazy<string> or by using something like _someValue = _someValue ?? InitializeMyValue(); as well but that's still more code to write than the new operator and less efficient as well. The Lazy<T> approach has some overhead and the null-coalescing operator + assignment has the added inefficiency of always making the variable assignment even if there is no need to (you can take a closer look at the ASM part of the SharpLab example above) but there it is for reference:

Hope this helps! :)

Sign up for more like this.

IMAGES

  1. Exploring Compound Assignment Operators in C

    compound assignment c#

  2. Compound Assignment Operators in C Programming Language

    compound assignment c#

  3. Compound Assignment Operators In C++

    compound assignment c#

  4. Assignment Operators in C++

    compound assignment c#

  5. PPT

    compound assignment c#

  6. Learn C++ Programming

    compound assignment c#

VIDEO

  1. Lesson16 Compound assignment with Arithmetic Operators & Assignment By Reference

  2. #20 Assignment Operators in C#

  3. Compound Assignment Operators in C++ || C++ Programming #viral #subscribe

  4. MAT112 GROUP ASSIGNMENT

  5. GROUP ASSIGNMENT MAT112 (COMPOUND INTEREST & ANNUITY)

  6. MAT112 ASSIGNMENT BA1111A_02 : COMPOUND INTEREST & ANNUITY

COMMENTS

  1. C# 8

    There are a lot of cool new features in C# 8 and one of my favorites is the new Null coalescing assignment (or compound assignment, whichever you prefer) operator. If you have ever written code like this: private string _someValue; public string SomeMethod() { // Let's do an old-school null check and initialize if needed.