Pherenetic
Pherenetic
CC#
Created by Pherenetic on 11/14/2024 in #help
NRT: How to correctly annotate my generic-class when inheriting from another generic class?
Hello. I'm trying to correctly annotate nullable reference types (NRT) to a generic class derived from another generic class. Here is some simplified code:
// Some dependency
interface IOther {
K? Get<K>();
}

// The derived class which I want to annotate correctly
public class MyDictionary<T,K> : Dictionary<T, K> where T: notnull {
public void Foo(T key) {
IOther x = null!;
Add(key, x.Get<K>()); // This triggers a CS8604
}
}

// Usage of the class
var tmp = new MyDictionary<Guid, string>();
tmp.Add(Guid.NewGuid(), null);
tmp.Add(Guid.NewGuid(), "null");
// Some dependency
interface IOther {
K? Get<K>();
}

// The derived class which I want to annotate correctly
public class MyDictionary<T,K> : Dictionary<T, K> where T: notnull {
public void Foo(T key) {
IOther x = null!;
Add(key, x.Get<K>()); // This triggers a CS8604
}
}

// Usage of the class
var tmp = new MyDictionary<Guid, string>();
tmp.Add(Guid.NewGuid(), null);
tmp.Add(Guid.NewGuid(), "null");
The shown implementation triggers the CS8604 as commented which I understand. But how do I tell the compiler: I don't know if the user will use a nullable type or not for K? When I change Dictionary<T, K> to Dictionary<T, K?> intellisense says that even my instance tmp can have nulls added but my type parameter clearly states that I don't want that to be allowed. So how do I correctly annotate this kind of scenario (I have a couple more like that)? Thanks in advance
60 replies