Essential C# 4.0 Mark Michaelis ptg Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City 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 trade- mark claim, the designations have been printed with initial capital letters or in all capitals. The .NET logo is either a registered trademark or trademark of Microsoft Corporation in the United States and/or other countries and is used under license from Microsoft. Microsoft, Windows, Visual Basic, Visual C#, and Visual C++ are either registered trademarks or trade- marks of Microsoft Corporation in the U.S.A. and/or other countries/regions. 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 [email protected] For sales outside the United States, please contact: International Sales ptg [email protected] Visit us on the Web: informit.com/aw Library of Congress Cataloging-in-Publication Data Michaelis, Mark. Essential C# 4.0 / Mark Michaelis. p. cm. Includes index. ISBN 978-0-321-69469-0 (pbk. : alk. paper) 1. C# (Computer program language) I. Title. QA76.73.C154M5237 2010 005.13’3—dc22 2009052592 Copyright © 2010 Pearson Education, Inc. All rights reserved. Printed in the United States of America. This publication is protected by copyright, 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-69469-0 ISBN-10: 0-321-69469-4 Text printed in the United States on recycled paper at Edwards Brothers in Ann Arbor, Michigan. First printing, March 2010 To my family: Elisabeth, Benjamin, Hanna, and Abigail. You have sacrificed a husband and daddy for countless hours of writing, frequently at times when he was needed most. Thanks! ptg This page intentionally left blank ptg Contents at a Glance Contents xi Contents of C# 4.0 Topics xxv Figures xxvii Tables xxix Foreword xxxi ptg Preface xxxv Acknowledgments xlvii About the Author li 1 Introducing C# 1 2 Data Types 31 3 Operators and Control Flow 83 4 Methods and Parameters 149 5 Classes 201 6 Inheritance 269 7 Interfaces 305 8 Value Types 331 9 Well-Formed Types 357 10 Exception Handling 405 11 Generics 421 12 Delegates and Lambda Expressions 469 ix x Contents of C# 4.0 Topics 13 Events 507 14 Collection Interfaces with Standard Query Operators 535 15 LINQ with Query Expressions 589 16 Building Custom Collections 611 17 Reflection, Attributes, and Dynamic Programming 651 18 Multithreading 701 19 Synchronization and More Multithreading Patterns 749 20 Platform Interoperability and Unsafe Code 815 21 The Common Language Infrastructure 843 A Downloading and Installing the C# Compiler and the CLI Platform 865 B Full Source Code Listings 869 C Concurrent Classes from System. Collections. Concurrent 895 D C# 2.0 Topics 899 ptg E C# 3.0 Topics 903 F C# 4.0 Topics 905 Index 907 Contents Contents of C# 4.0 Topics xxv Figures xxvii Tables xxix Foreword xxxi Preface xxxv Acknowledgments xlvii ptg About the Author li 1 Introducing C# 1 Hello, World 2 Compiling and Running the Application 3 C# Syntax Fundamentals 4 Type Definition 7 Main 8 Statements and Statement Delimiters 10 Whitespace 11 Working with Variables 12 Data Types 13 Declaring a Variable 14 Assigning a Variable 14 Using a Variable 16 Console Input and Output 16 Getting Input from the Console 16 Writing Output to the Console 18 Comments 20 Managed Execution and the Common Language Infrastructure 23 xi xii Contents C# and .NET Versioning 26 Common Intermediate Language and ILDASM 27 Summary 30 2 Data Types 31 Fundamental Numeric Types 32 Integer Types 32 Floating-Point Types (float, double) 33 Decimal Type 34 Literal Values 35 More Fundamental Types 40 Boolean Type (bool) 40 Character Type (char) 41 Strings 43 null and void 51 null 51 The void Nontype 52 Categories of Types 55 Value Types 55 Reference Types 56 ptg Nullable Modifier 57 Conversions between Data Types 58 Explicit Cast 58 Implicit Conversion 62 Type Conversion without Casting 62 Arrays 64 Declaring an Array 65 Instantiating and Assigning Arrays 66 Using an Array 70 Strings as Arrays 76 Common Errors 78 Summary 81 3 Operators and Control Flow 83 Operators 84 Plus and Minus Unary Operators (+, -) 84 Arithmetic Binary Operators (+, -, *, /, %) 85 Parenthesis Operator 92 Assignment Operators (+=, -=, *=, /=, %=) 93 Increment and Decrement Operators (++, --) 94 Constant Expressions (const) 98 Contents xiii Introducing Flow Control 98 if Statement 102 Nested if 103 Code Blocks ({}) 105 Scope and Declaration Space 107 Boolean Expressions 109 Relational and Equality Operators 110 Logical Boolean Operators 111 Logical Negation Operator (!) 113 Conditional Operator (?) 113 Null Coalescing Operator (??) 114 Bitwise Operators (<<, >>, |, &, ^, ~) 115 Shift Operators (<<, >>, <<=, >>=) 116 Bitwise Operators (&, |, ^) 117 Bitwise Assignment Operators (&=, |=, ^=) 120 Bitwise Complement Operator (~) 120 Control Flow Statements, Continued 121 The while and do/while Loops 121 The for Loop 124 The foreach Loop 127 The switch Statement 130 ptg Jump Statements 132 The break Statement 132 The continue Statement 135 The goto Statement 137 C# Preprocessor Directives 138 Excluding and Including Code (#if, #elif, #else, #endif) 140 Defining Preprocessor Symbols (#define, #undef) 141 Emitting Errors and Warnings (#error, #warning) 141 Turning Off Warning Messages (#pragma) 142 nowarn:<warn list> Option 143 Specifying Line Numbers (#line) 143 Hints for Visual Editors (#region, #endregion) 144 Summary 145 4 Methods and Parameters 149 Calling a Method 150 Namespace 152 Type Name 154 Scope 155 Method Name 155 Parameters 155