Search code examples
c#thrownull-coalescing-operator

The null-coalescing operator and throw


I've just noticed that when using throw with the null-coalescing operator, you cannot just use the keyword "throw" on its own, an exception must be included with it. The following code demonstrates what I mean:

try
{
   return GetName();
}
catch (NameNotFoundException ex)
{
    string name = GetOtherName();
    // this is legal
    return name ?? throw ex;
    // whereas this is not
    return name ?? throw;
}

Is there any reason for this? Would it be because throw; doesn't constitute an expression, or is there more to it?


Solution

  • According to https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.0/throw-expression

    a throw expression consists of the throw keyword followed by a null_coalescing_expression where the null_coalescing_expression

    must denote a value of the class type System.Exception, of a class type that derives from System.Exception or of a type parameter type that has System.Exception (or a subclass thereof) as its effective base class. If evaluation of the expression produces null, a System.NullReferenceException is thrown instead

    return name ?? throw; does not satisfy this condition as only the throw expression would be allowed here, not a throw statement.

    At least that's how I read this.