13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Simple generics for everyday use67I do not like green eggs and ham.";Dictionary frequencies = CountWords(text);foreach (KeyValuePair entry <strong>in</strong> frequencies){str<strong>in</strong>g word = entry.Key;<strong>in</strong>t frequency = entry.Value;Console.WriteL<strong>in</strong>e ("{0}: {1}", word, frequency);}Pr<strong>in</strong>ts eachkey/value pairfrom mapThe CountWords method B first creates an empty map from str<strong>in</strong>g to <strong>in</strong>t. This willeffectively count how often each word is used with<strong>in</strong> the given text. We then use a regularexpression C to split the text <strong>in</strong>to words. It’s crude—we end up with two empty str<strong>in</strong>gs(one at each end of the text), and I haven’t worried about the fact that “do” and “Do”are counted separately. These issues are easily fixable, but I wanted to keep the code assimple as possible for this example. For each word, we check whether or not it’s already<strong>in</strong> the map. If it is, we <strong>in</strong>crement the exist<strong>in</strong>g count; otherwise, we give the word an <strong>in</strong>itialcount of 1 D. Notice how the <strong>in</strong>crement<strong>in</strong>g code doesn’t need to do a cast to <strong>in</strong>t <strong>in</strong>order to perform the addition: the value we retrieve is known to be an <strong>in</strong>t at compiletime. The step <strong>in</strong>crement<strong>in</strong>g the count is actually perform<strong>in</strong>g a get on the <strong>in</strong>dexer forthe map, then <strong>in</strong>crement<strong>in</strong>g, then perform<strong>in</strong>g a set on the <strong>in</strong>dexer. Some developersmay f<strong>in</strong>d it easier to keep this explicit, us<strong>in</strong>g frequencies[word] = frequencies[word]+1; <strong>in</strong>stead.The f<strong>in</strong>al part of the list<strong>in</strong>g is fairly familiar: enumerat<strong>in</strong>g through a Hashtablegives a similar (nongeneric) DictionaryEntry with Key and Value properties foreach entry E. However, <strong>in</strong> <strong>C#</strong> 1 we would have needed to cast both the word and thefrequency as the key and value would have been returned as just object. That alsomeans that the frequency would have been boxed. Admittedly we don’t really have toput the word and the frequency <strong>in</strong>to variables—we could just have had a s<strong>in</strong>gle call toConsole.WriteL<strong>in</strong>e and passed entry.Key and entry.Value as arguments. I’ve reallyjust got the variables here to ram home the po<strong>in</strong>t that no cast<strong>in</strong>g is necessary.There are some differences between Hashtable and Dictionarybeyond what you might expect. We’re not look<strong>in</strong>g at them right now, but we’ll coverthem when we look at all of the .NET 2.0 collections <strong>in</strong> section 3.4. For the moment, ifyou experiment beyond any of the code listed here (and please do—there’s noth<strong>in</strong>glike actually cod<strong>in</strong>g to get the hang of a concept) and if it doesn’t do what you expect,just be aware that it might not be due to a lack of understand<strong>in</strong>g of generics. Checkthe documentation before panick<strong>in</strong>g!Now that we’ve seen an example, let’s look at what it means to talk aboutDictionary <strong>in</strong> the first place. What are TKey and TValue, and why dothey have angle brackets round them?3.2.2 Generic types and type parametersThere are two forms of generics: generic types (<strong>in</strong>clud<strong>in</strong>g classes, <strong>in</strong>terfaces, delegates,and structures—there are no generic enums) and generic methods. Both are essentiallya way of express<strong>in</strong>g an API (whether it’s for a s<strong>in</strong>gle generic method or a wholeELicensed to Rhona Hadida

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

Saved successfully!

Ooh no, something went wrong!