'Null-forgiving operator results in nullable type
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
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gunr2171 |
