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.

78 CHAPTER 3 Parameterized typ<strong>in</strong>g with genericsTable 3.2Examples of derivation type constra<strong>in</strong>tsDeclarationclass Samplewhere T : Streamstruct Samplewhere T : IDisposableclass Samplewhere T : IComparableclass Samplewhere T : UConstructed type examplesValid: SampleSampleInvalid: SampleSampleValid: SampleSampleInvalid: SampleValid: SampleInvalid: SampleValid: SampleSampleInvalid: Sampleparameter) and T : IList are also f<strong>in</strong>e. You can specify multiple <strong>in</strong>terfaces,but only one class. For <strong>in</strong>stance, this is f<strong>in</strong>e (if hard to satisfy):class Sample where T : Stream,IEnumerable,IComparableBut this isn’t:class Sample where T : Stream,ArrayList,IComparableNo type can derive directly from more than one class anyway, so such a constra<strong>in</strong>twould usually either be impossible (like this one) or part of it would be redundant(specify<strong>in</strong>g that the type had to derive from both Stream and MemoryStream, for example).One more set of restrictions: the class you specify can’t be a struct, a sealed class(such as str<strong>in</strong>g), or any of the follow<strong>in</strong>g “special” types:■■■■System.ObjectSystem.EnumSystem.ValueTypeSystem.DelegateDerivation type constra<strong>in</strong>ts are probably the most useful k<strong>in</strong>d, as they mean you canuse members of the specified type on <strong>in</strong>stances of the type parameter. One particularlyhandy example of this is T : IComparable, so that you know you can comparetwo <strong>in</strong>stances of T mean<strong>in</strong>gfully and directly. We’ll see an example of this (as well asdiscuss other forms of comparison) <strong>in</strong> section 3.3.3.COMBINING CONSTRAINTSI’ve mentioned the possibility of hav<strong>in</strong>g multiple constra<strong>in</strong>ts, and we’ve seen them <strong>in</strong>action for derivation constra<strong>in</strong>ts, but we haven’t seen the different k<strong>in</strong>ds be<strong>in</strong>gLicensed to Rhona Hadida

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

Saved successfully!

Ooh no, something went wrong!