Search code examples
c#c#-7.0null-coalescing

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?


Solution

  • 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