01_559885 ffirs.qxd 9/8/05 11:01 PM Page i Professional .NET 2.0 Generics Tod Golding 01_559885 ffirs.qxd 9/8/05 11:01 PM Page i Professional .NET 2.0 Generics Tod Golding 01_559885 ffirs.qxd 9/8/05 11:01 PM Page ii Copyright © 2005 by Wiley Publishing Inc. All rights reserved. Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA01923, (978) 750-8400, fax (978) 646-8700. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355,or online at http://www.wiley.com/go/permissions. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR APARTIC- ULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMO- TIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERYSITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PRO- FESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONALPERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOT THE AUTHOR SHALLBE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS ACITATION AND/OR A POTENTIALSOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAYMAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAYHAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. For general information on our other products and services please contact our Customer Care Depart- ment within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Trademarks: Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, and Programmer to Programmer are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Library of Congress Cataloging-in-Publication Data ISBN-13: 978-0-7645-5988-4 ISBN-10: 0-7645-5988-5 Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 01_559885 ffirs.qxd 9/16/05 9:35 AM Page iii About the Author Tod Goldinghas 20 years of experience as a software developer, lead architect, and development man- ager for organizations engaged in the delivery of large-scale commercial and internal solutions. He has an extensive background leveraging .NET, J2EE, and Windows DNAtechnologies, which has allowed him to become equally skilled with C#, Java, and C++. Tod has worked and consulted at a variety of companies, including stints with Microsoft and Borland. Tod has a B.S. in Computer Science from California State University, Sacramento. He started his writing career as a journalist for the Sacramento Beedaily newspaper. Prior to this book, he was also a contributing author for the XMLProgramming Bible, another Wiley publication. Tod currently resides in Sacramento, California, where he owns and operates Blue Puma Software. Credits Vice President and Executive Group Publisher: Development Editor: Richard Swadley Sharon Nash Vice President and Publisher: Production Editor: Joseph B. Wikert Felicia Robinson Acquisitions Editor: Technical Editor: Jim Minatel Mark A. Strawmyer Editorial Manager: Text Design & Composition: Mary Beth Wakefield Wiley Composition Services Senior Production Editor: Tim Tate 01_559885 ffirs.qxd 9/8/05 11:01 PM Page iv 01_559885 ffirs.qxd 9/8/05 11:01 PM Page v Acknowledgments Even though my name stands alone on the cover of this book, it certainly couldn’t have come to life without the support, encouragement, hard work, and creative input of many others. My family has to be at the top of the list of those that deserve thanks. The sacrifices made by my wife, Janine, during the past year were nothing short of heroic. Her support never waned, and I could not have finished this project without her. Thanks, too, to my children, Chelsea and Ryan, who always showed interest in my progress. Their smiling faces were always a great source of inspiration. I’d also like to thank everyone at Wiley Publishing. Without Jim Minatel’s insight and guidance, this book could not have gotten off the ground. His flexibility and willingness to work with a moving target provided me with the freedom this topic needed. I also can’t go without mentioning Wiley’s Sharon Nash and Felicia Robinson, who managed all the logistics associated with editing this book. Thanks, too, to Mark A. Strawmyer for all of his contributions on the technical editing front. There are also all those who helped push me along during the genesis of this book. My long-time friend, Bill Clark, provided perspective and creative influence that helped shape my approach to generics. Finally, special thanks go to Mike Cohn, who has always pushed me to take on new challenges. His early prodding and mastery of the 100-hour workweek clearly had the single greatest impact on getting me moving on this project. 01_559885 ffirs.qxd 9/8/05 11:01 PM Page vi 02_559885 ftoc.qxd 9/8/05 11:02 PM Page vii Contents Acknowledgments v Introduction xv Chapter 1: Generics 101 1 Why Generics? 1 Enter Generics 7 Hello Generics 10 A More Conceptual View 12 Terminology 14 Type Parameters 14 Open Types 15 Constructed Types 15 Type Arguments 15 Open and Closed Constructed Types 15 Generic Methods 16 Type Instantiation 16 Arity 17 Generic Types 17 Bringing It All Together 17 Summary 17 Chapter 2: Valuing Type Safety 19 Motivation 19 Least Common Denominator Programming 20 A Basic Example 21 Applying Generics 26 Casting Consequences 29 Interface Type Safety 31 Scratching the Surface 32 Safety vs. Clarity 32 Summary 33 Chapter 3: Generics ≠ Templates 35 Shared Concepts 35 Run-Time vs. Compile-Time 36 02_559885 ftoc.qxd 9/8/05 11:02 PM Page viii Contents Compile-Time Instantiation (Templates) 36 Run-Time Instantiation (Generics) 37 Lost in Translation 38 The Brouhaha 42 Code Bloat 42 Assemblies and Type Equivalence 42 Templates Extras 43 Template Specialization 43 Non-Type Parameters 44 Type Parameter Inheritance 44 Cross-Language Support 44 Debugging 44 Mix and Match Nirvana 44 Summary 45 Chapter 4: Generic Classes 47 Parameterizing Types 47 Type Parameters 49 Overloaded Types 50 Static Constructors 51 Inheritance 52 Protected Members 55 Fields 56 Static Fields 57 Constructed Fields 59 Methods 60 Overloading Methods 61 Overriding Methods 63 Arrays of Type Parameters 65 Operator Overloading 66 Nested Classes 67 Consuming Generic Classes 69 Accessibility 70 The Default Keyword 73 System.Nullable<T> 74 Accessing Type Info 76 Indexers,Properties,and Events 77 Generic Structs 80 Generic Interfaces 81 Summary 82 viii