Allow throw statements on the right hand of the null coalescening assignment operator #2091
-
In C# 8.0, this is valid code:
However, for some reason, this code is not
which would be a single line null check, but it generates CS8115 "A throw expression is not allowed in this context". Suggestion:Either
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
_ = x ?? throw new Exception(); is already valid, if you want a single line. |
Beta Was this translation helpful? Give feedback.
-
Whilst I can see a reason for making the compiler support if (x is null) throw new Exception(); as the intent of the code is then clear. I think this a case of "just because you can [or in theory could] express code in a certain way doesn't mean you should". |
Beta Was this translation helpful? Give feedback.
-
I won't say we can't be convinced to change our minds here, but this was a very explicit decision: https://github.com/dotnet/csharplang/blob/c81b99f4c965dbb6e9819a10a2e010db4c859f6f/meetings/2018/LDM-2018-07-16.md#throw-expression-on-the-right-hand-side. Our reasoning basically agreed with @DavidArno's above, we didn't see the benefits over a simple if statement. You're not trying to assign anything at all, you're doing a null check and throwing. |
Beta Was this translation helpful? Give feedback.
-
The code x ??= y; is not equivalent to x = x ?? y; rather it is equivalent to x ?? x = y; Which obviously would not permit the throw expression for |
Beta Was this translation helpful? Give feedback.
I won't say we can't be convinced to change our minds here, but this was a very explicit decision: https://github.com/dotnet/csharplang/blob/c81b99f4c965dbb6e9819a10a2e010db4c859f6f/meetings/2018/LDM-2018-07-16.md#throw-expression-on-the-right-hand-side. Our reasoning basically agreed with @DavidArno's above, we didn't see the benefits over a simple if statement. You're not trying to assign anything at all, you're doing a null check and throwing.