Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 322
Twenty Avatar asked Oct 14 '18 09:10

Twenty


2 Answers

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

like image 148
dialer Avatar answered Sep 29 '22 09:09

dialer


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.

like image 21
adjan Avatar answered Sep 29 '22 08:09

adjan