Search code examples
c#throwc#-7.0

Throw 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" );

Solution

  • 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.