Prev | Current Page 233 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"


The good news is that using a magic value doesn??™t waste any memory or need any
new types. However, it does rely on you picking an appropriate value that will never be
one you actually want to use for real data. Also, it??™s basically inelegant. It just doesn??™t
feel right. If you ever find yourself needing to go down this path, you should at least
have a constant (or static read-only value for types that can??™t be expressed as constants)
representing the magic value??”comparisons with DateTime.MinValue everywhere,
for instance, don??™t express the meaning of the magic value.
ADO.NET has a variation on this pattern where the same magic value??”
DBNull.Value??”is used for all null values, of whatever type. In this case, an extra value
and indeed an extra type have been introduced to indicate when a database has
returned null. However, it??™s only applicable where compile-time type safety isn??™t
important (in other words when you??™re happy to use object and cast after testing for
nullity), and again it doesn??™t feel quite right. In fact, it??™s a mixture of the ???magic value???
pattern and the ???reference type wrapper??? pattern, which we??™ll look at next.
115 System.Nullable and System.Nullable
PATTERN 2: A REFERENCE TYPE WRAPPER
The second solution can take two forms. The simpler one is to just use object as the
variable type, boxing and unboxing values as necessary.


Pages:
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245