Home > database >  Is is possible to make a generic method with two type arguments only infer one of them?
Is is possible to make a generic method with two type arguments only infer one of them?

Time:12-27

I have a method like public static TOut Method<TIn, TOut>(TIn in) with constraint where TIn: class, Interface<TOut>.

Do I always need to write Method<ClassIn, ClassOut>(ObjectIn); when I use it, or is there some way to make the TIn inferred by arguments so I only need to write Method<ClassOut>(ObjectIn);? The ClassOut varies from time to time so I can't write a static class for it every time.

Also, is it right that C# cannot infer types from the constraints so it is impossible to make both TIn and TOut inferred?

CodePudding user response:

Yes, you always need to specify both types. Type inference only works when you specify all the type arguments.

Yes, the C# compiler cannot infer types based on constraints. It can only infer the types based on the types you pass in as arguments.

On a side note, there is an open issue about improving type inference in this regard, however it doesn't seem to have high priority.

  • Related