Home > Software design >  Nullability of reference types in return type 'T? Manager<T>.Strategy.get' doesn
Nullability of reference types in return type 'T? Manager<T>.Strategy.get' doesn

Time:03-31

Using C# 10 I have:

public interface IStrategy<T> where T: Options { 
  T Options { get; }
}

public abstract class Strategy<T> : IStrategy<T> where T : Options {
  public abstract T Options { get; }
}

public interface IManager<T> where T: IStrategy<Options> {
  T Strategy { get; set; }
  Task Run();
}

public class Manager<T> : IManager<T> where T : IStrategy<Options> {

  public String Name { get; set; } 
  public T? Strategy { get; set; }

  public Manager(String name) {
    Name = name;
  }
}

I am getting the warning:

Nullability of reference types in return type of 'T? Manager<T>.Strategy.get' doesn't match implicitly implemented member 'T IManager<T>.Strategy.get' (possibly because of nullability attributes).  

I know that Strategy might be null in Manager because it might be set later and not in the constructor.

But Options in Strategy will never be null.

I have been changing T to T? but I always end up with a warning somewhere.

How to fix this?

CodePudding user response:

You can, but you are saying in your generics that you don't expect T to be null, then you are having a property whose getter (that's T IManager<T>.Strategy.get) might return a null T: that's the warning you are getting. Using only managed code and not reading externally (and unless you force the use of null explicitly), that should never happen (Strategy could never return null)

You can make it:

public class Manager<T> : IManager<T?> where T : IStrategy<Options> 
// Notice the ? in IManager<T?>

And the warning should go away, but think if that's what you actually want (that's precisely what nullable reference type annotations are for)

I've made a fiddle: https://dotnetfiddle.net/ccar24

  • Related