Null Coalescing Operator
One of my favorite C# features is the null-coalescing operator, which I've used for a long time:
// Simple fallback
var foo = specifiedValue ?? fallbackValue;
// Fetch if not present
foo = foo ?? getAFoo();
// Parameter validation
foo = foo ?? throw new ArgumentNullException(nameof(foo));
// Combination of the two previous examples
foo = foo ?? getAFoo() ?? throw new Exception("Couldn't track down a foo :( ");
Null-Coalescing Assignment Operator
I also like the new C# 8 operator that shortens the "fetch if not present" use case:
foo = foo ?? getAFoo(); // null-coalescing
foo ??= getAFoo(); // null-coalescing assignment
Question
I had hoped that perhaps I could use the null-coalescing assignment operator on the parameter validation use case as well, but it seems like it's not allowed. This is what I wanted to do:
foo = foo ?? throw new ArgumentNullException(nameof(foo)); // Does compile
foo ??= throw new ArgumentNullException(nameof(foo)); // Does not compile
Can anyone explain why the null-coalescing assignment operator works on the "fetch if not present" scenario but not on the parameter validation one?
https://dotnetfiddle.net/W8cNPo
Disclaimer
I realize that the ... ??= throw ... thing maybe isn't the most readable way to do this. My question isn't so much about style/readability as it is just trying to understand a quirk of this operator.
Thanks!