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.

68 CHAPTER 3 Parameterized typ<strong>in</strong>g with genericsgeneric type) such that <strong>in</strong> some places where you’d expect to see a normal type, yousee a type parameter <strong>in</strong>stead.A type parameter is a placeholder for a real type. Type parameters appear <strong>in</strong> anglebrackets with<strong>in</strong> a generic declaration, us<strong>in</strong>g commas to separate them. So <strong>in</strong> Dictionary the type parameters are TKey and TValue. When you use a generic typeor method, you specify the real types you want to use. These are called the typearguments—<strong>in</strong> list<strong>in</strong>g 3.1, for example, the type arguments were str<strong>in</strong>g (for TKey) and<strong>in</strong>t (for TValue).NOTE Jargon alert! There’s a lot of detailed term<strong>in</strong>ology <strong>in</strong>volved <strong>in</strong> generics.I’ve <strong>in</strong>cluded it for reference—and because very occasionally it makes iteasier to talk about topics <strong>in</strong> a precise manner. It could well be useful ifyou ever need to consult the language specification, but you’re unlikelyto need to use this term<strong>in</strong>ology <strong>in</strong> day-to-day life. Just gr<strong>in</strong> and bear it forthe moment.The form where none of the type parameters have been provided with type argumentsis called an unbound generic type. When type arguments are specified, the type is said tobe a constructed type. Unbound generic types are effectively bluepr<strong>in</strong>ts for constructedtypes, <strong>in</strong> a way similar to how types (generic or not) can be regarded as bluepr<strong>in</strong>ts forobjects. It’s a sort of extra layer of abstraction. Figure 3.1 shows this graphically.As a further complication, constructed types can be open or closed. An open type isone that <strong>in</strong>volves a type parameter from elsewhere (the enclos<strong>in</strong>g generic method orDictionary(unbound generic type)Specification oftype argumentsHashtableDictionary(constructed type)Dictionary(constructed type)(etc)InstantiationInstantiationInstantiationInstance ofHashtableInstance ofDictionaryInstance ofDictionaryNongenericbluepr<strong>in</strong>tsGenericbluepr<strong>in</strong>tsFigure 3.1 Unbound generic types act as bluepr<strong>in</strong>ts for constructed types, which then act as bluepr<strong>in</strong>tsfor actual objects, just as nongeneric types do.Licensed to Rhona Hadida

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

Saved successfully!

Ooh no, something went wrong!