Search code examples
c#nullable-reference-types

Fixing "CS8603: Possible null reference return" in method override


With the following code

abstract class Base
{
    protected abstract T? GetValue<T>([CallerMemberName] string propertyName = "");
}

class Derived : Base
{
    protected override T GetValue<T>([CallerMemberName] string propertyName = "")
    {
        return default;
    }
}

the compiler tells me at return default; that I have a CS8603 "Possible null reference return" which is true. However if I append a ? to the return type of that method so that reads (like the abstract method) protected override T? GetValue<T>([CallerMemberName] string propertyName = "") the compiler tells me

  • CS0508 'Derived.GetValue(string)': return type must be 'T' to match overridden member 'Base.GetValue(string)'.
  • CS0453 The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'.

How do I tell the compiler my intent that GetValue<T> might return a null reference and not that the return type of that method should be Nullable<T>?


Solution

  • The solution was to place the [return: MaybeNull] attribute on the method override as follows:

    [return: MaybeNull]
    protected override T GetValue<T>([CallerMemberName] string propertyName = "")
    {
      return default;
    }
    

    The compiler now no more lists warning CS8603.