简体   繁体   中英

Null coalescing operator (??) with return

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM