I've encountered a few times now where I have nullable enabled and a property or field marked as a nullable interface type (with an appended ?
), then if I go to use the property or field without a null check, I receive no error. (I would expect CS8602 - Dereference of a possibly null reference.
, and in concrete type properties and fields I do receive this error).
I am not sure if this is a Roslyn bug or something I don't adequately understand.
Additional information:
- .NET 5
- C# 9
namespace dotnet_scratch {
interface IFoo {
string? name { get; set; }
void fooAction ();
}
interface IFooGeneric<T> {
string? name { get; set; }
void fooAction( );
}
public class FooClass {
IFoo? fooInterface;
IFooGeneric<string>? fooInterfaceString;
FooClass? fooClass;
void doStuff( ) {
System.Console.WriteLine( fooInterface.name );
System.Console.WriteLine( fooInterfaceString.name );
fooInterface.fooAction();
fooInterfaceString.fooAction();
fooClass.fooAction();
}
void fooAction () {}
}
}
In the capture, the three highlighted errors are labeled:
(field) IFooGeneric<string>? FooClass.fooInterfaceString
'fooInterfaceString' may be null here.
Dereference of a possibly null reference. [dotnet_scratch]csharp(CS8602)
Additionally mousing over fooInterface.fooAction()
and fooInterfaceString.fooAction()
say:
'fooInterfaceString' is not null here.
My question is why is a property or field marked as IInterfaceType?
not flagged as being potentially Nullable as is the case with the concrete typed properties and fields?
name
... so if that hasn't failed, the value is definitely not null. (Your question is pretty unclear given that you do have warnings for the interface type, in the first two lines of the method...).name
references or I dofooInterface?.name
andfooInterfaceString?.name
the error is indeed shown on the twofooAction()
calls. Thank you, I do appreciate it. If you create that as an answer I will gladly mark it as correct. Otherwise I can do "Answer your question".