Advertisement
Intermediate C#, Generics

How does generic type inference work when calling a generic method, and when do you need to specify the type argument explicitly?

Short answer

The compiler infers a generic method's type argument(s) from the ARGUMENTS you actually pass, when possible — you only need to specify the type argument explicitly in angle brackets when it CAN'T be inferred from the arguments alone, like when the type only appears in the return…

Save C# mock interview
Advertisement
AModel answer
The compiler infers a generic method's type argument(s) from the ARGUMENTS you actually pass, when possible — you only need to specify the type argument explicitly in angle brackets when it CAN'T be inferred from the arguments alone, like when the type only appears in the return type or the method has no arguments at all.
public T CreateDefault<T>() where T : new() => new T();

// Can't infer T from arguments (there are none) -- must specify explicitly
var user = CreateDefault<User>();

public void Print<T>(T value) => Console.WriteLine(value);
Print(42); // T inferred as int automatically from the argument
Real-world example
Understanding exactly when you're required to write `<T>` explicitly versus when the compiler figures it out for you.
Likely follow-ups
  • What happens if the compiler CAN'T unambiguously infer T even from the provided arguments?
Related topics