Express expressions not working for boolean expressions?

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" ); 
+5
source share
2 answers

From the original github suggestion :

The throw expression is allowed only in the following syntax contexts:

  • As the second or third operand of the ternary conditional operator ?:
  • As the second operand of the zero coalescence operator ??
  • Like the body of a pronounced lambda or method.

These are three cases where throw expressions can be used. Thus, your use of a throw in a boolean expression is not considered and is not a valid syntax.

+8
source

The answer is "because the spec says I can't." But the more interesting question is: why does the specification talk about this? In short, I think because it will ruin the logic. The throw expression has no logical meaning. An expression of expressions is just a shortcut in the syntax. We can get away from it only when the return value of the throw expression or its absence does not matter. On the other hand, for logical logic, the return value matters.

+1
source

Source: https://habr.com/ru/post/1271906/


All Articles