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.

70 CHAPTER 3 Parameterized typ<strong>in</strong>g with generics}{}: IEnumerablepublic Dictionary(){[...]}Declaresparameterlessconstructorpublic void Add (TKey key, TValue value){[...]}public TValue this [TKey key]{get { [...] }set { [...] }}public bool Conta<strong>in</strong>sValue (TValue value){[...]}public bool Conta<strong>in</strong>sKey (TKey key){[...]}[... other members ...]Implementsgeneric <strong>in</strong>terfaceDeclares methodus<strong>in</strong>g typeparametersNotice how Dictionary implements the generic <strong>in</strong>terface IEnumerable (and many other <strong>in</strong>terfaces <strong>in</strong> real life). Whatever typearguments you specify for the class are applied to the <strong>in</strong>terface where the same typeparameters are used—so <strong>in</strong> our example, Dictionary implementsIEnumerable. Now that’s actually sort of a “doublygeneric” <strong>in</strong>terface—it’s the IEnumerable <strong>in</strong>terface, with the structure KeyValue-Pair as the type argument. It’s because it implements that <strong>in</strong>terface thatlist<strong>in</strong>g 3.1 was able to enumerate the keys and values <strong>in</strong> the way that it did. It’s also worthpo<strong>in</strong>t<strong>in</strong>g out that the constructor doesn’t list the type parameters <strong>in</strong> angle brackets. Thetype parameters belong to the type rather than to the particular constructor, so that’swhere they’re declared.Generic types can effectively be overloaded on the number of type parameters—soyou could def<strong>in</strong>e MyType, MyType, MyType, MyType, and so forth, allwith<strong>in</strong> the same namespace. The names of the type parameters aren’t used when consider<strong>in</strong>gthis—just how many there are of them. These types are unrelated except <strong>in</strong>name—there’s no default conversion from one to another, for <strong>in</strong>stance. The same istrue for generic methods: two methods can be exactly the same <strong>in</strong> signature otherthan the number of type parameters.Licensed to Rhona Hadida

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

Saved successfully!

Ooh no, something went wrong!