Roslyn: Can't use ?. in an expression returning a ReadOnlySpan

Created on 19 Nov 2019  路  2Comments  路  Source: dotnet/roslyn

Version Used: Visual Studio 16.4 preview 4

Steps to Reproduce:

Compile the following:

using System;
public class C
{
    public ReadOnlySpan<char> M(string? s)
    {
        return s?.AsSpan() ?? throw new ArgumentNullException();
    }
}

Expected Behavior:

Compiles without error

Actual Behavior:

Error CS0023 Operator '?' cannot be applied to operand of type 'ReadOnlySpan'

Area-Compilers Concept-Diagnostic Clarity Feature Request help wanted

Most helpful comment

@CyrusNajmabadi has very kindly explained to me why this error occurs, but I think the error message is extremely confusing, so I will leave this open so it can hopefully be labelled with diagnostic-clarity.

A better message would be "? operator cannot be used in expression returning type of ReadOnlySpan as it would require creating a temporary Nullable of a ref type".

All 2 comments

@CyrusNajmabadi has very kindly explained to me why this error occurs, but I think the error message is extremely confusing, so I will leave this open so it can hopefully be labelled with diagnostic-clarity.

A better message would be "? operator cannot be used in expression returning type of ReadOnlySpan as it would require creating a temporary Nullable of a ref type".

Seems like when the type ReadOnlySpan<char>? appears in source we use this diagnostic:

  <data name="ERR_BadTypeArgument" xml:space="preserve">
    <value>The type '{0}' may not be used as a type argument</value>
  </data>

Don't know how helpful that is though for providing inspiration for how to phrase a better diagnostic for a?.AsSpan().

Was this page helpful?
0 / 5 - 0 ratings