ptg Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City Essential C# 4.0 Mark Michaelis From the Library of Wow! eBook 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 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 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 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 St ates on recycled pap er at Edwards Brothers in Ann Arbor, Michigan. First printing, March 2010 From the Library of Wow! eBook ptg To my f am il y: E li sa be th , Benja mi n, H an na , an d Ab ig ail. You h av e sa cr ific ed a h us band a nd d addy f or c ou ntle ss h ou rs o f wri ti ng , frequently at times when he was needed most. Thanks! From the Library of Wow! eBook ptg This page intentionally left blank From the Library of Wow! eBook ptg ix Contents at a Glance Contents xi Contents of C# 4.0 Topics xxv Figures xxvii Ta bl es xxix Foreword xxxi 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 From the Library of Wow! eBook ptg Contents of C# 4.0 Topicsx 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 E C# 3.0 Topics 903 F C# 4.0 Topics 905 Index 907 From the Library of Wow! eBook ptg xi Contents of C# 4.0 Topics xxv Figures xxvii Ta bl es x xi x Foreword xxxi Preface xxxv Acknowledgments xlvii 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 Contents From the Library of Wow! eBook ptg Contentsxii 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 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 From the Library of Wow! eBook ptg 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 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 Tur nin g O ff War nin g Me ssag es (#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 From the Library of Wow! eBook ptg Contentsxiv Method Return 155 Statement versus Method Call 156 Declaring a Method 157 Parameter Declaration 159 Method Return Declaration 159 The using Directive 161 Aliasing 164 Returns and Parameters on Main() 165 Parameters 168 Value Parameters 168 Reference Parameters (ref) 170 Output Parameters (out) 171 Parameter Arrays (params) 173 Recursion 176 Method Overloading 179 Optional Parameters 182 Basic Error Handling with Exceptions 186 Tra ppin g E rrors 18 7 Reporting Errors Using a throw Statement 196 Summary 199 5 Classes 201 Declaring and Instantiating a Class 205 Instance Fields 209 Declaring an Instance Field 209 Accessing an Instance Field 210 Instance Methods 211 Using the this Keyword 213 Access Modifiers 220 Properties 222 Declaring a Property 223 Automatically Implemented Properties 225 Naming Conventions 227 Using Properties with Validation 228 Read-Only and Write-Only Properties 230 Access Modifiers on Getters and Setters 231 Properties as Virtual Fields 232 Properties and Method Calls Not Allowed as ref or out Parameter Values 234 Constructors 236 Declaring a Constructor 237 Default Constructors 239 Object Initializers 239 From the Library of Wow! eBook [...]... 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 E C# 3.0 Topics 903 F C# 4.0 Topics Index 905 907 From the Library of Wow! eBook This page intentionally left blank From the Library of Wow! eBook Contents of C# 4.0 Topics 4 Methods and Parameters Common Namespaces 153 Optional Parameters 182 9 Well-Formed... those not already familiar with them Also pertinent to advanced C# development is the subject of pointers, in Chapter 21 Even experienced C# developers often do not understand this topic well Features of This Book Essential C# 4.0 is a language book that adheres to the core C# Language 4.0 Specification To help you understand the various C# constructs, the book provides numerous examples demonstrating... Execution 752 Interlock’s Synchronization-Related Methods 762 Execution Path with ManualResetEvent Synchronization 770 Concurrent Collection Classes 773 Overview of the Various Timer Characteristics 779 Table 21.1: Table 21.2: Primary C# Compilers 845 Common C #- Related Acronyms 862 491 585 712 From the Library of Wow! eBook Foreword MARK MICHAELIS S OVERVIEW OF THE C# language has become a standard reference... Mono, Rotor, and Microsoft NET platforms Platformor vendor-specific libraries are seldom used, except when communicating important concepts relevant only to those platforms (appropriately handling the single-threaded user interface of Windows, for example) Any code that specifically requires C# 3.0 or 4.0 compliance is called out in the C# 3.0 and C# 4.0 indexes at the end of the book From the Library of... to the C# language will give developers access to late-bound languages such as Python and Ruby Improved support for COM Interop will allow developers to access Microsoft Office with an intuitive and easy-to-use syntax that makes these great tools easy to use Mark s coverage of these important topics, along with his explanation of the latest developments in concurrent development, make this an essential. .. way that I can understand.” Mark Michaelis is a one-man solution to a C# developer’s search for knowledge about Microsoft’s most recent technologies xxxi From the Library of Wow! eBook xxxii Foreword I first met Mark at a breakfast held in Redmond, Washington, on a clear, sunny morning in the summer of 2006 It was an early breakfast, and I like to sleep in late But I was told Mark was an active community... audience needs to hear and he enjoys teaching Mark knows not only the C# language, but also the English language He knows how to craft a sentence, how to divide his thoughts into paragraphs and subsections, and how to introduce and summarize a topic He consistently finds clear, easy-to-understand ways to explain complex subjects I read the first edition of Mark s book cover to cover in just a few evenings... programming, and so on Although these topics are relevant to the NET Framework, to do them justice requires books of their own Fortunately, Addison-Wesley’s NET Development Series provides a wealth of writing on these topics Essential C# 4.0 focuses on C# and the types within the Base Class Library Reading this book will prepare you to focus on and develop expertise in any of the areas covered by the... and FORTRAN is still significant but shrinking, so it behooves software engineers to become familiar with object-oriented development C# is an ideal language for making this transition because it was designed with object-oriented development as one of its core tenets • Object-based and object-oriented developers: C++ and Java programmers, and many experienced Visual Basic programmers, fall into this... of the Data 832 Figure 21.1: Compiling C# to Machine Code 848 Figure 21.2: Assemblies with the Modules and Files They Reference 856 From the Library of Wow! eBook Tables Table 1.1: C# Keywords 5 Table 1.2: C# Comment Types 21 Table 1.3: C# and NET Versions 26 Table 2.1: Table 2.2: Table 2.3: Table 2.4: Table 2.5: Table 2.6: Table 2.7: Integer Types 32 Floating-Point Types 33 decimal Type 34 Escape . Inc. Rights and Contracts Department 501 Boylston Street, Suite 900 Boston, MA 02 116 Fax: (617) 67 1- 344 7 ISBN-13: 978 -0 - 32 1-6 946 9 -0 ISBN- 10: 0- 32 1-6 946 9 -4 Text printed in the United St ates on. of Congress Cataloging-in-Publication Data Michaelis, Mark. Essential C# 4. 0 / Mark Michaelis. p. cm. Includes index. ISBN 978 -0 - 32 1-6 946 9 -0 (pbk. : alk. paper) 1. C# (Computer program language). Guidelines 40 0 Lazy Initialization 40 0 Summary 40 3 10 Exception Handling 40 5 Multiple Exception Types 40 5 Catching Exceptions 40 7 General Catch Block 40 9 Guidelines for Exception Handling 41 1 Defining