3.3 Implementing generics
Although you??™re likely to spend more time using generic types and methods than writing
them yourself, there are a few things you should know for those occasions where
you??™re providing the implementation. Most of the time you can just pretend T (or whatever
your type parameter is called) is just the name of a type and get on with writing
code as if you weren??™t using generics at all. There are a few extra things you should
know, however.
DEFAULT VALUE EXPRESSIONS
When you know exactly what type you??™re working with, you know its ???default??? value??”
the value an otherwise uninitialized field would have, for instance. When you don??™t
know what type you??™re referring to, you can??™t specify that default value directly. You
can??™t use null because it might not be a reference type. You can??™t use 0 because it
might not be a numeric type. While it??™s fairly rare to need the default value, it can be
useful on occasion. Dictionary
provides a good example??”it has a
TryGetValue method that works a bit like the TryParse methods on the numeric
types: it uses an output parameter for the value you??™re trying to fetch, and a Boolean
return value to indicate whether or not it succeeded. This means that the method has
to have some value of type TValue to populate the output parameter with. (Remember
that output parameters must be assigned before the method returns normally.
Pages:
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181