I'm playing around a bit with the new C# 8 nullable reference types feature, and while refactoring my code I came upon this (simplified) method:
public T Get<T>(string key)
{
var wrapper = cacheService.Get(key);
return wrapper.HasValue ? Deserialize<T>(wrapper) : default;
}
Now, this gives a warning
Possible null reference return
which is logical, since default(T)
will give null for all reference types. At first I thought I would change it to the following:
public T? Get<T>(string key)
But this cannot be done. It says I either have to add a generic constraint where T : class
or where T : struct
. But that is not an option, as it can be both (I can store an int
or int?
or an instance of FooBar
or whatever in the cache).
I also read about a supposed new generic constraint where class?
but that did not seem to work.
The only simple solution I can think of is changing the return statement using a null forgiving operator:
return wrapper.HasValue ? Deserialize<T>(wrapper) : default!;
But that feels wrong, since it can definitely be null, so I'm basically lying to the compiler here..
How can I fix this? Am I missing something utterly obvious here?
Nullable<T>
and reference types at the same time. This looks like just a continuation of that issue. The only good workaround I have found is writing both aGet
andGetStruct
version of these kinds of methods. – Dave Cousineau