How to get the C# compiler to infer generic types?

c#, compiler-construction

Solution

The C# specification does not allow inferring half of type arguments. You should either let the compiler to infer all the type arguments (which is not always applicable, like in your case) or manually specify all of them.

UPDATE (reply to comment): While I'm not on the C# team to give an absolute answer to your question, my speculation is that the complexity of overload resolution (which is already mind-blowing; you know that if you read that section of C# specification) would increase significantly if they wanted to allow half of types to be inferred and half not (especially considering the fact that you can overload methods solely by the number of generic arguments).

Problem

I have the following method: ``` public TResult Get<TGenericType, TResult>() where TGenericType : SomeGenericType<TResult> where TResult : IConvertible { //...code that uses TGenericType... //...code that sets someValue... return (TResult) someValue; } ``` Right now, a user of this method has to use it like this: ``` //Notice the duplicate int type specification int number = Get<SomeGenericType<int>, int>(); ``` Why do I have to specify TResult in the method defintion? The compiler already knows TResult since I specified it in TGenericType. Ideally (if the C# compiler was a little smarter), my method would look like this: ``` public TResult Get<TGenericType>() where TGenericType : SomeGenericType<TResult> where TResult : IConvertible { //...code that uses TGenericType... //...code that sets someValue... return (TResult) someValue; } ``` So the user could just simply use it like this: ``` //Much cleaner int number = Get<SomeGenericType<int>>(); ``` Is there a way to do what I want to do?

Original source