Limitations of C# generic type inference
C#’s type inference mechanism can usually intelligently infer the generic parameters of generic methods. However, type inference may fail in some cases, as shown in the following example:
<code class="language-csharp">interface IQuery<TResult> { } interface IQueryProcessor { TResult Process<TQuery, TResult>(TQuery query) where TQuery : IQuery<TResult>; } class SomeQuery : IQuery<string> { }</code>
In the above code, when calling SomeQuery
's IQueryProcessor
method using a Process
instance, the compiler is unable to infer the correct generic parameters. Explicitly specifying the parameters solves this problem:
<code class="language-csharp">p.Process<SomeQuery, string>(query);</code>
Reason for inference failure
Contrary to initial assumptions, constraints alone are not sufficient for type inference. C#'s type inference is entirely based on parameters and their corresponding formal parameter types. Since the provided parameter type is SomeQuery
(which implements IQuery<string>
), the compiler cannot automatically infer that the generic parameters should be TQuery = SomeQuery
and TResult = string
.
Eric Lippert in the article "Constraints are not part of the signature" (https://www.php.cn/link/4cf06252cc21d496e754ad7185d0617d.
The above is the detailed content of Why Does C# Generic Type Inference Fail with Interface Constraints?. For more information, please follow other related articles on the PHP Chinese website!