class Sample
{
public static T M<T, TParam1>(TParam1 param1)
{
return default(T);
}
}
class Program
{
static void Main(string[] args)
{
double d = Sample.M((int)121);
}
}
This code doesn’t compile and results in the following error message:
The type arguments for method
‘ThreadPoolTest.Sample.M(TParam1)’ cannot be inferred from
the usage. Try specifying the type arguments
explicitly
Why isn’t type inference working in this example?
Type inference can only use the arguments to the method call. The fact that you’re assigning the result to a
doubleis entirely irrelevant as far as type inference is concerned. In other words, as far as the compiler is concerned, it needs to work out what this means:without any more information. For example, you could mean
Sample.M<int, int>, orSample.M<double, int>, orSample.M<string, int>– there’s no information so say which of those is a better match.You don’t mention
Tin the parameter list, so type inference can’t help.