This area is already fairly complicated in C# 2, and
C# 3 takes things even further. I won??™t try to give all of the nuts and bolts of the C# 2 rules
here, but the basic steps are as follows.
1 For each method argument (the bits in normal parentheses, not angle brackets),
try to infer some of the type arguments of the generic method, using some
fairly simple techniques.
2 Check that all the results from the first step are consistent??”in other words, if
one argument implied one type argument for a particular type parameter, and
another implied a different type argument for the same type parameter, then
inference fails for the method call.
3 Check that all the type parameters needed for the generic method have been
inferred. You can??™t let the compiler infer some while you specify others explicitly
??”it??™s all or nothing.
To avoid learning all the rules (and I wouldn??™t recommend it unless you??™re particularly
interested in the fine details), there??™s one simple thing to do: try it to see what happens.
If you think the compiler might be able to infer all the type arguments, try calling the
method without specifying any. If it fails, stick the type arguments in explicitly. You lose
nothing more than the time it takes to compile the code once, and you don??™t have to
have all the extra language-lawyer garbage in your head.
81 Beyond the basics
3.
Pages:
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180