Reputation: 5961
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?
Upvotes: 8
Views: 1014
Reputation: 4844
throw
has relatively recently (in C# 7.0) been turned into an expression to enable this. return
hasn't - it is a full 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
Upvotes: 11
Reputation: 13684
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.
Upvotes: 1