Why doesn't C# infer my generic types?
A bunch of people have pointed out that C# does not make inferences based on constraints. That is correct, and relevant to the question. Inferences are made by examining arguments and their corresponding formal parameter types and that is the only source of inference information.
A bunch of people have then linked to this article:
https://docs.microsoft.com/en-us/archive/blogs/ericlippert/c-3-0-return-type-inference-does-not-work-on-method-groups
That article is both out-of-date and irrelevant to the question. It is out-of-date because it describes a design decision we made in C# 3.0 which we then reversed in C# 4.0, mostly based on the response to that article. I've just added an update to that effect to the article.
It is irrelevant because the article is about return type inference from method group arguments to generic delegate formal parameters. That is not the situation the original poster asks about.
The relevant article of mine to read is rather this one:
https://docs.microsoft.com/en-us/archive/blogs/ericlippert/constraints-are-not-part-of-the-signature
UPDATE: I have heard news that C# 7.3 has slightly changed the rules for when constraints are applied, making the above ten-year-old article no longer accurate. When I have time I'll review the changes my former colleagues have made and see if it is worthwhile to post a correction on my new blog; until then, use caution and see what C# 7.3 does in practice.
C# will not infer generic types based on the return type of a generic method, only the arguments to the method.
It also doesn't use the constraints as part of the type inference, which eliminates the generic constraint from supplying the type for you.
For details, see Eric Lippert's post on the subject.
It doesn't use constraints to infer types. Rather it infers types (when possible) and then checks constraints.
Therefore, while the only possible TResult
that could be used with a SomeQuery
parameter, it won't see this.
Note also, that it would be perfectly possible for SomeQuery
to also implement IQuery<int>
, which is one reason why this is limitation on the compiler may not be a bad idea.