Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Type inference: How to properly define constraints on method?

Hi I am having hard time making C# type inference do what I want. I have a very specific situation where I have a lot of variables in the flavor of

ConcurrentDictionary<T, IDictionary<U, V> >

where T,U,V can be some random types like long, int or whatever.

I want to write the method that works with this types of variables - notably examines their histograms.

So I have written a method

public static IOrderedEnumerable<Tuple<int,int>> GetDictionaryHistogram<T, U, V, W>(T dictionary) where T : ConcurrentDictionary<U, IDictionary<V, W>>
{
    return dictionary.Select(p => p.Value.Count)
                     .GroupBy(p => p)
                     .Select(p => new Tuple<int, int>(p.Key, p.Count()))
                     .OrderBy(p => p.Item1);
}

But when I try to call it, C# gives me an error that it cannot infer the types. For example on a variable of type

ConcurrentDictionary<int,IDictionary<int, int> > foo;

I get the error:

Error 118 The type arguments for method 'Auditor.AuditorHelpers.GetDictionaryHistogram(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

What did I do wrong?

like image 545
luckyluke Avatar asked Nov 27 '25 17:11

luckyluke


1 Answers

Type inference infers from arguments to formal parameter types. No inferences are ever made on constraints because constraints are not a part of the signature of a method.

In your case type inference must always fail; type inference cannot possibly infer types for U and V because they do not appear in a formal parameter type.

For about a dozen people telling me that I am wrong to believe that this rule is sensible, see the comments to my article on the subject.

like image 102
Eric Lippert Avatar answered Nov 30 '25 05:11

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!