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
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! :)
IMAGES
VIDEO
COMMENTS
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.