I am wondering if there is a specific reason why the C# compiler does not seem to support two-level type inference on generics.
See the following code sample:
class Program
{
static void Main(string[] args)
{
var instance = new GenericClass<object>();
Test<GenericClass<object>, object>(instance); // works
Test(instance); // Type arguments cannot be inferred
}
static void Test<TGenericClass, T>(TGenericClass obj)
where TGenericClass : IGenericClass<T>
{
}
}
public class GenericClass<T> : IGenericClass<T>
{
public T Prop { get; set; }
}
public interface IGenericClass<T>
{
T Prop { get; set; }
}
The compiler cannot infer that an object of type GenericClass<object>
respects the type constraints, instead I have to specify the types manually. Is there a reason why the compiler does not support inference across multiple levels? How do you usually deal with it?
EDIT: Assume TGenericClass
has to be generic.