Prev | Current Page 266 | Next

Jon Skeet

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

5 With nullable types, this pattern
can be extended to value types??”and in fact, it??™s safer with value types, because if
the natural result type is a value type, then a null value could only be returned as a failure
case. Nullable types add that extra Boolean piece of information in a nice generic
way with language support??”so why not use them?
To demonstrate this pattern in practice and in a context other than dictionary
lookups, I??™ll use the classic example of the TryXXX pattern??”parsing an integer. The
implementation of the TryParse method in listing 4.5 shows the version of the pattern
using an output parameter, but then we see the use of the version using nullable
types in the main part at the bottom.
static int? TryParse (string data)
{
int ret;
if (int.TryParse(data, out ret))
{
return ret;
}
else
{
return null;
}
}
...
int? parsed = TryParse("Not valid");
if (parsed != null)
{
Console.WriteLine ("Parsed to {0}", parsed.Value);
}
5 Wouldn??™t it be great if Hashtable and Dictionary could take a delegate to call whenever a
new value was required due to looking up a missing key? Situations like this would be a lot simpler.
Listing 4.5 An alternative implementation of the TryXXX pattern
Classic call with
output parameter
Nullable
call
133 Novel uses of nullable types
else
{
Console.WriteLine ("Couldn't parse");
}
You may well think there??™s very little to distinguish the two versions here??”they??™re the
same number of lines, after all.


Pages:
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278