Today, we’ll keep looking at generics and we’ll see how type inference is used to simplify the code we need to write to invoke a method. Lets start with a simple example:
And yes, you can also define generics at the method level…Now, without type inference, we would have to specify the type of the generic type arguments expected by the method:
The good news is that the MS team added generic type arguments inference. In practice, this means that we can simply call the method *without* explicitly specifying its type arguments:
Now, there’s one important detail which might get you by surprise…Take a look at the following snippet:
What will appear in the console now? If you’re thinking that the type will be System.Int32 like in the previous snippet, you’re wrong. You see, the compiler uses the variable’s data type (instead of the actual type of the object referred by that variable) when it has to infer the generic argument type. Another interesting aspect of using generics with methods is trying to understand how thing works with overloads. What should happen when the compiler finds these method overloads:
Yes, it does compile…but how does the compiler find the correct method for each of the following calls:
As you can see, the compiler will always choose a more specific call over a generic match (and that’s why the first method ends up being invoked for the first call). Notice also that when you explicitly specify the generic type argument, then the compiler is obliged to call the generic method.
And I guess that’s all for now. Stay tuned for more.