I'm having lots of Funcy fun (fun intended) with generic methods. In most cases C# type inference is smart enough to find out what generic arguments it must use on my generic methods, but now I've got a design where the C# compiler doesn't succeed, while I believe it could have succeeded in finding the correct types.
Can anyone tell me whether the compiler is a bit dumb in this case, or is there a very clear reason why it can't infer my generic arguments?
Here's the code:
Classes and interface definitions:
interface IQuery<TResult> { }
interface IQueryProcessor
{
TResult Process<TQuery, TResult>(TQuery query)
where TQuery : IQuery<TResult>;
}
class SomeQuery : IQuery<string>
{
}
Some code that does not compile:
class Test
{
void Test(IQueryProcessor p)
{
var query = new SomeQuery();
// Does not compile :-(
p.Process(query);
// Must explicitly write all arguments
p.Process<SomeQuery, string>(query);
}
}
Why is this? What am I missing here?
Here's the compiler error message (it doesn't leave much to our imagination):
The type arguments for method IQueryProcessor.Process<TQuery, TResult>(TQuery) cannot be inferred from the usage. Try specifying the type arguments explicitly.
The reason I believe C# should be able to infer it is because of the following:
- I supply an object that implements
IQuery<TResult>
. - That only
IQuery<TResult>
version that type implements isIQuery<string>
and thus TResult must bestring
. - With this information the compiler has TResult and TQuery.