2

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?

Romulus Urakagi Ts'ai
  • 3,699
  • 10
  • 42
  • 68
  • 1
    You could put it into a static generic class `MyClass` then you only need to specify `ClassOut` because the method will be inferred – Charlieface Dec 27 '21 at 03:40
  • Does this answer your question? [Partial generic type inference possible in C#?](https://stackoverflow.com/questions/2893698/partial-generic-type-inference-possible-in-c) – Charlieface Dec 27 '21 at 03:40
  • @Charlieface Seems not. It looks like a different story as I don't use extensions and the answers use `this` argument to infer the type. Also, my question was not clear enough that the `ClassOut` is not a fixed class but more like a type argument. – Romulus Urakagi Ts'ai Dec 27 '21 at 06:36
  • Similar issue though, it's caused by the same compiler problem. But perhaps this link is better https://stackoverflow.com/questions/10719557/c-sharp-generic-type-inference-with-multiple-types – Charlieface Dec 27 '21 at 07:13

1 Answers1

4

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.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166