Home > Software engineering >  Null-forgiving operator results in nullable type
Null-forgiving operator results in nullable type

Time:04-20

I've a .NET 6.0 C# console project with the property <Nullable>enable</Nullable>. In it, I've the following, where Span is a primitive data type:

sealed class PrivateParser {
   private void FatalError(int msgId, Span span /*, ...*/) {
       /* ... */
   }
}

When I call FatalError(), immediately forgiving null in the second agument:

FatalError(0x80A0400, id.Span!);

The compiler outputs:

error CS1503: Argument 2: cannot convert from
'ShockBasic.Semantics.SourceData.Span?' to
'ShockBasic.Semantics.SourceData.Span' [C:\Users\hando\Documents\shockbasic\sb\ShockBasic.Compiler.csproj]

See Microsoft docs, the operator should return the non-nullable type, thus I'm a bit lost.

To reproduce it, the full project is in this GitHub commit. Run dotnet build and you can look at the last error. Locations

CodePudding user response:

From the docs that you have added in the question:

you use the null-forgiving operator to declare that expression x of a reference type isn't null.

Span is a value type. To change "Nullable value type" (in your case (Nullable<Span>/Span?) To non nullable, when calling the method you should use FatalError(0x80A0400, id.Span.Value);, but that may throw InvalidOperationException (docs) when the id.Span will be null

  • Related