I have an extension method like this:
[return: MaybeNull]
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
where TKey : notnull
where TValue : notnull {
if (dictionary.TryGetValue(key, out TValue value)) return value;
else return default!;
}
This works fine. Were I to call it expecting a non-null value, the compiler warns me the results could be null, which is exactly what I want.
However, if I have another method that calls GetValueOrDefault
, and I forget to add the [return: MaybeNull]
, the compiler won't warn me at all. Here's a convoluted example just to explain my issue:
public static TValue SomeOtherMethod<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
where TKey : notnull
where TValue : notnull
=> dictionary.GetValueOrDefault(key); // No warning this could be null
...
var dictionary = new Dictionary<string, string>() {
["hello"] = "world"
};
string s1 = dictionary.GetValueOrDefault("foo"); // Compiler warning
string s2 = dictionary.SomeOtherMethod("foo"); // No compiler warning
int s2Len = s2.Length; // Visual Studio states "s2 is not null here", even though it absolutely is!
I'm pretty new to C# 8.0 nullable reference types, especially involving generics. Is there anything I'm missing to get this to work? Without the compiler warning, it feels like it defeats the purpose of using C# 8.0 nullable types. I'm lulled into a false sense of security that I couldn't possibly miss a NullReferenceException, especially when Visual Studio reassures me "s2 is not null here" even though it absolutely is.