© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•15mo ago•
59 replies
Pherenetic

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
K
?
When I change
Dictionary<T, K>
Dictionary<T, K>
to
Dictionary<T, K?>
Dictionary<T, K?>
intellisense says that even my instance
tmp
tmp
can have
null
null
s 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
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

❔ How to access variable from another class?
C#CC# / help
3y ago
How to refer to the mainwindow class from another class.
C#CC# / help
2y ago
✅ How to deserialize JSON in .NET when my base class is generic?
C#CC# / help
3y ago