I'm writing up a generic method that needs to internally use a Dictionary
keyed by the generic parameter.
I don't want to impose any constraint on the generic parameter itself, in particular no notnull
constraint. However, the method would be capable of handling nulls explicitly, and of course not adding any null keys to the dictionary it's using.
Is there any best practice for doing so?
By default, the compiler warns that the generic key type doesn't match the notnull
constraint of Dictionary<,>
.
See an example below. Unless I'm missing something, this should be perfectly safe. But how can I best convey this to the compiler? Is there any way other than suppressing the compiler warning here?
public static int CountMostFrequentItemOrItems<T>(params T[] values)
{
var counts = new Dictionary<T, int>(); // The type 'T' cannot be used as type parameter 'TKey' in the generic type or method 'Dictionary<TKey, TValue>'
var nullCount = 0;
foreach(var value in values)
if (value is null)
++nullCount;
else if (counts.TryGetValue(value, out var count))
counts[value] = count+1;
else
counts[value] = 1;
// ... combine results etc ...
}