The compiler allows you to omit
it, leaving this:
List
list = MakeList ("Line 1", "Line 2");
That??™s a bit neater, isn??™t it? At least, it??™s shorter. That doesn??™t always mean it??™s more
readable, of course??”in some cases it??™ll make it harder for the reader to work out what
type arguments you??™re trying to use, even if the compiler can do it easily. I recommend
that you judge each case on its merits.
Notice how the compiler definitely knows that we??™re using string as the type
parameter, because the assignment to list works too, and that still does specify the
type argument (and has to). The assignment has no influence on the type parameter
inference process, however. It just means that if the compiler works out what type arguments
it thinks you want to use but gets it wrong, you??™re still likely to get a compiletime
error.
How could the compiler get it wrong? Well, suppose we actually wanted to use
object as the type argument. Our method parameters are still valid, but the compiler
thinks we actually meant to use string, as they??™re both strings. Changing one of the
parameters to explicitly be cast to object makes type inference fail, as one of the
method arguments would suggest that T should be string, and the other suggests that
T should be object. The compiler could look at this and say that setting T to object
would satisfy everything but setting T to string wouldn??™t, but the specification only gives
a limited number of steps to follow.
Pages:
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179