Again, there are two ways of implementing this solution.
Either you could maintain two separate variables in the code that uses the value, or
you could encapsulate the ???value plus flag??? into another value type.
This latter solution is quite similar to the more complicated reference type idea
described earlier, except that you avoid the garbage-collection issue by using a value
type, and indicate nullity within the encapsulated value rather than by virtue of a null
reference. The downside of having to create a new one of these types for every value
type you wish to handle is the same, however. Also, if the value is ever boxed for some
reason, it will be boxed in the normal way whether it??™s considered to be null or not.
The last pattern (in the more encapsulated form) is effectively how nullable types
work in C# 2. We??™ll see that when the new features of the framework, CLR, and language
are all combined, the solution is significantly neater than anything that was possible in
C# 1. Our next section deals with just the support provided by the framework and the
CLR: if C# 2 only supported generics, the whole of section 4.2 would still be relevant and
the feature would still work and be useful. However, C# 2 provides extra syntactic sugar
to make it even better??”that??™s the subject of section 4.3.
4.2 System.Nullable
and System.Nullable
The core structure at the heart of nullable types is System.
Pages:
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247