Type Inference in Generics

If you are using generic method, you can call the method without explicitly specifying the type arguments. Their are certain cases where the compiler cannot infer the type based on the values passed in the parameters, in those cases you can explicitly specify the type argument. Depending on the scenario,it might be concise syntax but may not be readable to another developer. Here is an example of using generic method with and without explicitly specifying the type.

image

 

In the above example I have a generic method which is constrained to have a parameter of type T that needs to implement IComparable<T>. By enforcing this constraint, I can make sure that the argument passed in can be checked against compareTo method to compare two parameters. As far as using the method, in the first case I pass in integers. The first example shows that I am not specifying the type of parameters passed in. In fact compiler is using type inference to determine the exact type of variables being passed. Further down I pass in strings where in the first case I don't specify the type and let compiler determine the type and than I also illustrate the usage in which I am explicitly specifying the type. Some readers may find specifying the type to be more readable because it shows the intent of the programmer even though the compiler can infer the type. The scenario where type inference will fail for generic method, would be where certain parameters can be inferred where as other cant. In those cases type inference would completely fail. It has to be all or none.

No Comments