I have a question for C# 8 nullable reference type in a static class. Here is my original code.
public static class Foo
{
private static IFactory _factory;
public static void Init(IFactory factory) => _factory = factory;
public static string GetVersion() => _factory.GetVersion();
}
Now I have a warning
private static IFactory _factory; //Non-nullable field is uninitialized. Consider declaring the field as nullable.
Which is correct, as without calling the Init()
, _factory
will be null
. But I will call Init()
at the very beginning of the program.
So I make it nullable private static IResultFactory? _factory;
and the warning is gone.
But I got one more warning
public static string GetVersion() => _factory.GetVersion(); //Dereference of a possibly null reference.
Here I know that by the time I got here it will not be null
, any elegant way other than the ! (null-forgiving) operator
?
Or is there something else I am missing to solve this gratefully?
Update: I know for a method there are some tips and tricks, for example:
internal static T NotNull<T>([NotNull] this T? value) where T : class =>
value ?? throw new ArgumentNullException(nameof(value));
Here it's saying the return will not be null
, just to get rid of the warning.
I'm wondering is there something similar to this.
System.Lazy<IFactory>
– Aluan Haddad