Prev | Current Page 265 | Next

Jon Skeet

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

NET Framework. I have no issues with the aims??”the idea that some
methods are likely to fail to perform their primary purpose in nonexceptional circumstances
is common sense. My one problem with it is that I??™m just not a huge fan
of output parameters. There??™s something slightly clumsy about the syntax of declaring
a variable on one line, then immediately using it as an output parameter.
Methods returning reference types have often used a pattern of returning null
on failure and non-null on success. It doesn??™t work so well when null is a valid return
value in the success case. Hashtable is an example of both of these statements, in a
132 CHAPTER 4 Saying nothing with nullable types
slightly ambivalent way. You see, null is a theoretically valid value in a Hashtable, but
in my experience most uses of Hashtable never use null values, which makes it perfectly
acceptable to have code that assumes that a null value means a missing key.
One common scenario is to have each value of the Hashtable as a list: the first time
an item is added for a particular key, a new list is created and the item added to it.
Thereafter, adding another item for the same key involves adding the item to the
existing list. Here??™s the code in C# 1:
ArrayList list = hash[key];
if (list==null)
{
list = new ArrayList();
hash[key] = list;
}
list.Add(newItem);
Hopefully you??™d use variable names more specific to your situation, but I??™m sure you
get the idea and may well have used the pattern yourself.


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