13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

132 CHAPTER 4 Say<strong>in</strong>g noth<strong>in</strong>g with nullable typesslightly ambivalent way. You see, null is a theoretically valid value <strong>in</strong> a Hashtable, but<strong>in</strong> my experience most uses of Hashtable never use null values, which makes it perfectlyacceptable to have code that assumes that a null value means a miss<strong>in</strong>g key.One common scenario is to have each value of the Hashtable as a list: the first timean item is added for a particular key, a new list is created and the item added to it.Thereafter, add<strong>in</strong>g another item for the same key <strong>in</strong>volves add<strong>in</strong>g the item to theexist<strong>in</strong>g list. Here’s the code <strong>in</strong> <strong>C#</strong> 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 youget the idea and may well have used the pattern yourself. 5 With nullable types, this patterncan be extended to value types—and <strong>in</strong> fact, it’s safer with value types, because ifthe natural result type is a value type, then a null value could only be returned as a failurecase. Nullable types add that extra Boolean piece of <strong>in</strong>formation <strong>in</strong> a nice genericway with language support—so why not use them?To demonstrate this pattern <strong>in</strong> practice and <strong>in</strong> a context other than dictionarylookups, I’ll use the classic example of the TryXXX pattern—pars<strong>in</strong>g an <strong>in</strong>teger. Theimplementation of the TryParse method <strong>in</strong> list<strong>in</strong>g 4.5 shows the version of the patternus<strong>in</strong>g an output parameter, but then we see the use of the version us<strong>in</strong>g nullabletypes <strong>in</strong> the ma<strong>in</strong> part at the bottom.List<strong>in</strong>g 4.5An alternative implementation of the TryXXX patternstatic <strong>in</strong>t? TryParse (str<strong>in</strong>g data){<strong>in</strong>t ret;Classic call withif (<strong>in</strong>t.TryParse(data, out ret)) output parameter{return ret;}else{return null;}}...Nullable<strong>in</strong>t? parsed = TryParse("Not valid"); callif (parsed != null){Console.WriteL<strong>in</strong>e ("Parsed to {0}", parsed.Value);}5Wouldn’t it be great if Hashtable and Dictionary could take a delegate to call whenever anew value was required due to look<strong>in</strong>g up a miss<strong>in</strong>g key? Situations like this would be a lot simpler.Licensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!