Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw Expressions not working for Boolean expressions?

Tags:

c#

throw

c#-7.0

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" );
like image 825
HappyNomad Avatar asked Sep 18 '17 15:09

HappyNomad


2 Answers

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.

like image 79
David Arno Avatar answered Oct 15 '22 03:10

David Arno


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.

like image 31
HappyNomad Avatar answered Oct 15 '22 02:10

HappyNomad