www.it-ebooks.info ptg Effective C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City www.it-ebooks.info ptg Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U.S. Corporate and Government Sales (800) 382-3419 corpsales@pearsontechgroup.com For sales outside the United States please contact: International Sales international@pearson.com Visit us on the Web: informit.com/aw Library of Congress Cataloging-in-Publication Data Wagner, Bill. Effective C# : 50 specific ways to improve your C# / Bill Wagner.–2nd ed. p. cm. Includes index. ISBN 978-0-321-65870-8 (pbk. : alk. paper) 1. C# (Computer program language) 2. Database management. 3. Microsoft .NET Framework. I. Title. QA76.73.C154W343 2010 005.13'3–dc22 2009052199 Copyright © 2010 Pearson Education, Inc. All rights reserved. Printed in the United States of America. This publication is protected by copy- right, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to: Pearson Education, Inc. Rights and Contracts Department 501 Boylston Street, Suite 900 Boston, MA 02116 Fax: (617) 671-3447 ISBN-13: 978-0-321-65870-8 ISBN-10: 0-321-65870-1 Te x t p r i n t e d i n t h e U n i t e d S t a t e s o n r e c y c l e d p a p e r a t C o u r i e r i n S t o u g h t o n , M a s s a c h u s e t t s . First printing, March 2010 www.it-ebooks.info ptg To my parents, Bill and Alice Wagner. They continue to demonstrate great strength and inspiration. www.it-ebooks.info ptg This page intentionally left blank www.it-ebooks.info ptg ❘ Contents at a Glance ix Introduction xiii Chapter 1 C# Language Idioms 1 Chapter 2 .NET Resource Management 69 Chapter 3 Expressing Designs in C# 125 Chapter 4 Working with the Framework 179 Chapter 5 Dynamic Programming in C# 227 Chapter 6 Miscellaneous 275 Index 309 www.it-ebooks.info ptg This page intentionally left blank www.it-ebooks.info ptg ❘ Contents xi Introduction xiii Chapter 1 C# Language Idioms 1 Item 1: Use Properties Instead of Accessible Data Members 1 Item 2: Prefer readonly to const 8 Item 3: Prefer the is or as Operators to Casts 12 Item 4: Use Conditional Attributes Instead of #if 20 Item 5: Always Provide ToString() 28 Item 6: Understand the Relationships Among the Many Different Concepts of Equality 36 Item 7: Understand the Pitfalls of GetHashCode() 44 Item 8: Prefer Query Syntax to Loops 51 Item 9: Avoid Conversion Operators in Your APIs 56 Item 10: Use Optional Parameters to Minimize Method Overloads 60 Item 11: Understand the Attraction of Small Functions 64 Chapter 2 .NET Resource Management 69 Item 12: Prefer Member Initializers to Assignment Statements 74 Item 13: Use Proper Initialization for Static Class Members 77 Item 14: Minimize Duplicate Initialization Logic 79 Item 15: Utilize using and try/finally for Resource Cleanup 87 Item 16: Avoid Creating Unnecessary Objects 94 Item 17: Implement the Standard Dispose Pattern 98 Item 18: Distinguish Between Value Types and Reference Types 104 Item 19: Ensure That 0 Is a Valid State for Value Types 110 Item 20: Prefer Immutable Atomic Value Types 114 Chapter 3 Expressing Designs in C# 125 Item 21: Limit Visibility of Your Types 126 Item 22: Prefer Defining and Implementing Interfaces to Inheritance 129 Item 23: Understand How Interface Methods Differ from Virtual Methods 139 Item 24: Express Callbacks with Delegates 143 Item 25: Implement the Event Pattern for Notifications 146 Item 26: Avoid Returning References to Internal Class Objects 154 www.it-ebooks.info ptg Item 27: Prefer Making Your Types Serializable 157 Item 28: Create Large-Grain Internet Service APIs 166 Item 29: Support Generic Covariance and Contravariance 171 Chapter 4 Working with the Framework 179 Item 30: Prefer Overrides to Event Handlers 179 Item 31: Implement Ordering Relations with IComparable<T> and IComparer<T> 183 Item 32: Avoid ICloneable 190 Item 33: Use the new Modifier Only to React to Base Class Updates 194 Item 34: Avoid Overloading Methods Defined in Base Classes 198 Item 35: Learn How PLINQ Implements Parallel Algorithms 203 Item 36: Understand How to Use PLINQ for I/O Bound Operations 215 Item 37: Construct Parallel Algorithms with Exceptions in Mind 220 Chapter 5 Dynamic Programming in C# 227 Item 38: Understand the Pros and Cons of Dynamic 227 Item 39: Use Dynamic to Leverage the Runtime Type of Generic Type Parameters 236 Item 40: Use Dynamic for Parameters That Receive Anonymous Types 239 Item 41: Use DynamicObject or IDynamicMetaObjectProvider for Data-Driven Dynamic Types 243 Item 42: Understand How to Make Use of the Expression API 254 Item 43: Use Expressions to Transform Late Binding into Early Binding 261 Item 44: Minimize Dynamic Objects in Public APIs 267 Chapter 6 Miscellaneous 275 Item 45: Minimize Boxing and Unboxing 275 Item 46: Create Complete Application-Specific Exception Classes 279 Item 47: Prefer the Strong Exception Guarantee 284 Item 48: Prefer Safe Code 294 Item 49: Prefer CLS-Compliant Assemblies 298 Item 50: Prefer Smaller, Cohesive Assemblies 303 Index 309 xii ❘ Contents www.it-ebooks.info ptg ❘ Introduction xiii The C# community is very different in 2010 than it was in 2004 when the first edition of Effective C# was published. There are many more develop- ers using C#. A large contingent of the C# community is now seeing C# as their first professional language. They aren’t approaching C# with a set of ingrained habits formed using a different language. The community has a much broader range of experience. New graduates all the way to profes- sionals with decades of experience are using C#. The C# language has also grown in the last five years. The language I cov- ered in the first edition did not have generics, lambda expressions, LINQ, and many of the other features we now take for granted. C# 4.0 adds new features that change our toolset again. And yet, even with all the growth in the C# language, much of the original advice is as relevant now as it was in the C# 1.x days. Viewed in hindsight, the changes to the C# language appear to be natural and obvious extensions to what we had in C# 1.0. New editions give us new ways of solving problems, without invalidating previous idioms. I organized this second edition of Effective C# by taking into account both the changes in the language and the changes in the C# community. Effec- tive C# does not take you on a historical journey through the changes in the language. Rather, I provide advice on how to use the current C# lan- guage. The items that have been removed from this second edition are those that aren’t as relevant in today’s C# language. The new items cover the new language and framework features, and those practices the com- munity has learned from building several versions of software products using C#. Overall, these items are a set of recommendations that will help you use C# 4.0 more effectively as a professional developer. This book covers C# 4.0, but it is not an exhaustive treatment of the new language features. Like all books in the Effective Software Development Series, this book offers practical advice on how to use these features to solve problems you’re likely to encounter every day. Many of the items are equally valid in the 3.0 and even earlier versions of the language. www.it-ebooks.info [...]... crept into the text or samples If you believe you have found an error, please contact me at bill.wagner@srtsolutions.com Errata will be posted at http://srtsolutions.com/blogs/effectivecsharp Many of the items in this book, and More Effective C#, are the result of email conversations with other C# developers If you have questions or comments about the recommendations, please contact me Discussions of general... in common with a familiar language, such as C++ or Java C# is another curly braced language, making it easy to fall into the same idioms you used in other languages in the same family That will prevent you from getting the most out of C# The C# language has evolved since its first commercial release in 2001 It’s now much farther removed from C++ or Java than it was in its original release If you are... serves as Michigan’s Regional Director for Microsoft and is a multiyear winner of Microsoft’s MVP award An internationally recognized writer, Bill is the author of the first edition of this book and More Effective C# (Addison-Wesley, 2009) and currently writes a column on the Microsoft C# Developer Center Bill earned a B.S in computer science from the University of Illinois at ChampaignUrbana www.it-ebooks.info...xiv ❘ Introduction Who Should Read This Book? Effective C# was written for professional developers who use C# as part of their daily toolset It assumes you are familiar with the C# syntax and the language’s features The second edition assumes you . will be posted at http://srtsolutions.com/blogs/effectivecsharp. Many of the items in this book, and More Effective C#, are the result of email conversations. informit.com/aw Library of Congress Cataloging-in-Publication Data Wagner, Bill. Effective C# : 50 specific ways to improve your C# / Bill Wagner.–2nd ed. p.