Throw Expressions work in this case:
string myStr;
public MyObj( string myStr ) =>
this.myStr = myStr ?? throw new ArgumentNullException( "myStr" );
But why doesn't this compile too?
bool isRunning;
public void Run() =>
isRunning = !isRunning || throw new InvalidOperationException( "Already running" );
From the original proposal on github:
A throw expression is permitted in only the following syntactic contexts:
- As the second or third operand of a ternary conditional operator
?:
- As the second operand of a null coalescing operator
??
- As the body of an expression-bodied lambda or method.
These are the only three cases where throw expressions can be used. Thus your use of a throw in a boolean expression isn't covered and isn't valid syntax.
The answer is, "because the spec says I can't". But the more interesting question is, why does the spec say that? In short, I think it's because it would mess up Boolean logic. A throw expression doesn't have a Boolean value. Throw expressions are just a shortcut in syntax. We can only get away with it when the throw expression's return value, or lack thereof, doesn't matter. For Boolean logic to work, on the other hand, the return value does matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With