I was wondering why it is possible to do this in C# 7.0:
int? test = 0;
int test2 = test ?? throw new Exception("Error");
..but not this:
int? test = 0;
int test2 = test ?? return;
Can someone explain that?
throw
has relatively recently (in C# 7.0) been turned into an expression to enable this. return
hasn't - it is always a just statement. The ??
operator requires an expression, not a statement. It was an arbitrary choice by the C# designers, specifically to allow using throw
with ??
.
See the documentation on the throw
expression
Well, because no one has implemented it this way. Or, more precisely, because return
is not an expression.
throw
used to be a statement only prior to C# 7.0, but then was extended (due to a proposal) to be an expression as well (only expressions are supported in the null coalescing operator).
So unless no one suggests to make return
an expression, it won't work.
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