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 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
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.
ix
Contents at a Glance
Contents xi
Contents of C# 4.0 Topics xxv Figures xxvii
Tables 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
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
xi
Contents of C# 4.0 Topics xxv Figures xxvii
Tables xxix 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
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
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 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
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 Trapping Errors 187
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
Contents xv
Overloading Constructors 241 Constructor Chaining: Calling another
Constructor Using this 243 Static Members 247
Static Fields 248 Static Methods 251 Static Constructors 253 Static Properties 254 Static Classes 255 Extension Methods 256 Encapsulating the Data 258
const 258 readonly 259 Nested Classes 260 Partial Classes 262
Defining a Partial Class 263 Partial Methods 264 Summary 267
6
Inheritance 269
Derivation 270
Casting between Base and Derived Types 272 private Access Modifier 275
protected Access Modifier 276 Extension Methods 278
Single Inheritance 278 Sealed Classes 281
Overriding the Base Class 281 virtual Modifier 282
new Modifier 286 sealed Modifier 291 base Member 291 Constructors 292 Abstract Classes 293
All Classes Derive from System.Object 299
Verifying the Underlying Type with the is Operator 301 Conversion Using the as Operator 302
Summary 303
7
Interfaces 305
Introducing Interfaces 306
Explicit Member Implementation 314 Implicit Member Implementation 315
Explicit versus Implicit Interface Implementation 316 Converting between the Implementing Class and Its
Interfaces 318
Interface Inheritance 318
Multiple Interface Inheritance 321 Extension Methods on Interfaces 322
Implementing Multiple Inheritance via Interfaces 323 Versioning 326
Interfaces Compared with Classes 328 Summary 329
8
Value Types 331
Structs 332
Initializing structs 336
Using the default Operator 338
Inheritance and Interfaces with Value Types 338 Boxing 339
Enums 346
Type Compatibility between Enums 349 Converting between Enums and Strings 350 Enums as Flags 351
Summary 356
9
Well-Formed Types 357
Overriding object Members 357 Overriding ToString() 358 Overriding GetHashCode() 358 Overriding Equals() 361
Guidelines for Implementing Equality 369 Operator Overloading 369
Comparison Operators (==, !=, <, >, <=, >=) 370 Binary Operators (+, -, *, /, %, &, |, ^, <<, >>) 371
Combining Assignment with Binary Operators (+=, -=, *=, /=, %=, &=…) 373 Conditional Logical Operators (&&, ||) 373
Unary Operators (+, -, !, ~, ++, --, true, false) 373 Conversion Operators 375
Guidelines for Conversion Operators 377 Referencing Other Assemblies 377
Contents xvii
Defining Namespaces 382 Namespace Alias Qualifier 384 XML Comments 385
Associating XML Comments with Programming Constructs 386 Generating an XML Documentation File 388
Garbage Collection 390 Weak References 391 Resource Cleanup 393
Finalizers 393
Deterministic Finalization with the using Statement 395 Garbage Collection and Finalization 398
Resource Utilization and Finalization Guidelines 400 Lazy Initialization 400
Summary 403
10
Exception Handling 405
Multiple Exception Types 405 Catching Exceptions 407 General Catch Block 409
Guidelines for Exception Handling 411 Defining Custom Exceptions 414 Summary 419
11
Generics 421
C# without Generics 422 Introducing Generic Types 427
Using a Generic Class 427
Defining a Simple Generic Class 429 Benefits of Generics 430
Type Parameter Naming Guidelines 431 Generic Interfaces and Structs 432
Defining a Constructor and a Finalizer 434 Specifying a Default Value 435
Multiple Type Parameters 436 Arity in Abundance 437 Nested Generic Types 438 Constraints 439
Generic Methods 453 Type Inferencing 454 Specifying Constraints 455
Covariance and Contravariance 457
Enabling Covariance with the out Type Parameter Modifier in C# 4.0 458 Enabling Contravariance with the in Type Parameter Modifier in C# 4.0 460 Support for Parameter Covariance and Contravariance in Arrays 462 Generic Internals 463
Instantiating Generics Based on Value Types 464 Instantiating Generics Based on Reference Types 465 Summary 467
12
Delegates and Lambda Expressions 469
Introducing Delegates 470 Defining the Scenario 470 Delegate Data Types 472 Delegate Internals 473 Defining a Delegate Type 474 Instantiating a Delegate 475 Anonymous Methods 480
System-Defined Delegates: Func<> 483 Lambda Expressions 486
Statement Lambdas 486 Expression Lambdas 489 Outer Variables 495 Expression Trees 498 Summary 506
13
Events 507
Coding the Observer Pattern with Multicast Delegates 508 Defining Subscriber Methods 508
Defining the Publisher 510
Hooking Up the Publisher and Subscribers 511 Invoking a Delegate 512
Check for null 513 Delegate Operators 514 Sequential Invocation 516 Error Handling 519
Method Returns and Pass-by-Reference 522 Events 523
Contents xix
Generics and Delegates 528
Customizing the Event Implementation 532 Summary 533
14
Collection Interfaces with Standard Query Operators 535
Anonymous Types and Implicitly Typed Local Variables 536 Anonymous Types 537
Implicitly Typed Local Variables (var) 538
More about Anonymous Types and Implicit Local Variables 540 Collection Initializers 543
What Makes a Class a Collection: IEnumerable<T> 546 foreach with Arrays 546
foreach with IEnumerable<T> 547
Do Not Modify Collections during foreach Iteration 552 Standard Query Operators 552
Filtering with Where() 556 Projecting with Select() 557 Counting Elements with Count() 561 Deferred Execution 562
Sorting with OrderBy() and ThenBy() 566 Performing an Inner Join with Join() 572 Grouping Results with GroupBy() 575
Implementing a One-to-Many Relationship with GroupJoin() 577 Calling SelectMany() 580
More Standard Query Operators 582 Summary 586
15
LINQ with Query Expressions 589
Introducing Query Expressions 590 Projection 592
Filtering 598 Sorting 599 The Let Clause 600 Grouping 602
Query Continuation with into 605
Query Expressions as Method Invocations 608 Summary 609
16
Building Custom Collections 611
More Collection Interfaces 612
IList<T> versus IDictionary<TKey, TValue> 614 IComparable<T> 614
Primary Collection Classes 617 List Collections: List<T> 617
Dictionary Collections: Dictionary<TKey, TValue> 622 Sorted Collections: SortedDictionary<TKey, TValue> and
SortedList<T> 626 Stack Collections: Stack<T> 628 Queue Collections: Queue<T> 629 Linked Lists: LinkedList<T> 629 Providing an Index Operator 630
Returning Null or an Empty Collection 634 Iterators 634
Defining an Iterator 636 Iterator Syntax 636
Yielding Values from an Iterator 637 Iterators and State 639
More Iterator Examples 641
Placing a yield return within a Loop 643 Canceling Further Iteration: yield break 645 Creating Multiple Iterators in a Single Class 648 yield Statement Characteristics 649
Summary 650
17
Reflection, Attributes, and Dynamic Programming 651
Reflection 652
Accessing Metadata Using System.Type 653 Member Invocation 655
Reflection on Generic Types 660 Attributes 663
Custom Attributes 666 Looking for Attributes 667
Initializing an Attribute through a Constructor 668 System.AttributeUsageAttribute 673 Named Parameters 674
Programming with Dynamic Objects 688 Invoking Reflection Using dynamic 689 dynamic Principles and Behaviors 690 Why Dynamic Binding? 694
Static Compilation versus Dynamic Programming 695 Implementing a Custom Dynamic Object 696
Contents xxi
18
Multithreading 701
Running and Controlling a Separate Thread 706 ContinueWith() 711
Unhandled Exception Handling on Task 715 Canceling a Task 718
Long-Running Tasks 722 Disposing a Task 723
Executing Iterations in Parallel 724
Parallel Exception Handling with System.AggregateException 728 Canceling a Parallel Loop 729
Running LINQ Queries in Parallel 734 Canceling a PLINQ Query 736
Multithreading before .NET Framework 4 738
Asynchronous Operations with System.Threading.Thread 738 Thread Management 740
Thread Pooling 742
Unhandled Exceptions on the AppDomain 744 Summary 746
19
Synchronization and More Multithreading Patterns 749
Synchronization 750
Synchronization Using Monitor 754 Using the lock Keyword 757 Choosing a lock Object 758
Why to Avoid Locking on this, typeof(type), and string 759 Declaring Fields as volatile 760
Using the System.Threading.Interlocked Class 761 Event Notification with Multiple Threads 763
Synchronization Design Best Practices 764 More Synchronization Types 766
Thread Local Storage 774 Timers 778
Asynchronous Programming Model 783 Calling the APM 784
Calling the APM Using TPL 791
Asynchronous Delegate Invocation 797 Passing Data to and from an Alternate Thread 799 Event-Based Asynchronous Pattern (EAP) 801 Background Worker Pattern 804
Windows UI Programming 809 Windows Forms 809
Windows Presentation Foundation (WPF) 811 Summary 814
20
Platform Interoperability and Unsafe Code 815
Platform Invoke 816
Declaring External Functions 817 Parameter Data Types 818
Using ref Rather Than Pointers 819
Using StructLayoutAttribute for Sequential Layout 820 Error Handling 821
Using SafeHandle 823 Calling External Functions 826
Simplifying API Calls with Wrappers 828 Function Pointers Map to Delegates 829 Guidelines 829
Pointers and Addresses 830 Unsafe Code 830
Pointer Declaration 832 Assigning a Pointer 834 Dereferencing a Pointer 837
Accessing the Member of a Referent Type 839 Summary 839
21
The Common Language Infrastructure 843
Defining the Common Language Infrastructure (CLI) 844 CLI Implementations 845
C# Compilation to Machine Code 847 Runtime 849
Garbage Collection 849
Garbage Collection on .NET 850 Type Safety 851
Code Access Security 852 Platform Portability 852 Performance 853
Application Domains 854
Assemblies, Manifests, and Modules 855 Common Intermediate Language (CIL) 858 Common Type System (CTS) 858
Contents xxiii
Base Class Library (BCL) 860 Metadata 860
Summary 862
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
xxv
Contents of C# 4.0 Topics
4
Methods and Parameters
Common Namespaces 153 Optional Parameters 182
9
Well-Formed Types
Generics
Lazy Loading With 401
Use of System.Exception 412 Tuple Generic Types 437
11
Generics
Generics
Enabling Covariance 458 Enabling Contravariance 460
Support for Covariance and Contravariance 462
12
Delegates and Lambda Expressions
System-Defined Delegates: Func 483 Parallel LINQ (PLINQ) 559
Programming with Dynamic Objects 688
18
Multithreading 701
Running Threads 706
Long-Running Threads 722 Disposing Tasks 723
Executing Iterations in Parallel 724 Parallel Exception Handling with
System.AggregateException 728 Canceling Parallel Loops 729
Running LINQ Queries in Parallel 734
Multithreading, Unhandled Exceptions on AppDomain 744
19
Synchronization and More Multithreading Patterns 749
Monitor Class Synchronization 754 lock Keyword 757
Reset Events 768
ManualResetEvent and Semaphores over AutoReset Event 772 Concurrent Collection Classes 773
Thread Local Storage 774
xxvii
Figures
Figure 2.1: Value Types Contain the Data Directly 55 Figure 2.2: Reference Types Point to the Heap 56
Figure 3.1: Corresponding Placeholder Values 115
Figure 3.2: Calculating the Value of an Unsigned Byte 116 Figure 3.3: Calculating the Value of a Signed Byte 116 Figure 3.4: The Numbers 12 and 7 Represented in Binary 118 Figure 3.5: Collapsed Region in Microsoft Visual Studio .NET 145
Figure 4.1: Exception-Handling Program Flow 190
Figure 5.1: Class Hierarchy 204
Figure 6.1: Refactoring into a Base Class 271
Figure 6.2: Working around Multiple Inheritance Using Aggregation 280
Figure 7.1: Working around Single Inheritances with Aggregation and
Interfaces 326
Figure 8.1: Value Types Contain the Data Directly 332 Figure 8.2: Reference Types Point to the Heap 333
Figure 9.1: Identity 362
Figure 9.2: XML Comments as Tips in Visual Studio IDE 386
Figure 12.1: Delegate Types Object Model 474 Figure 12.2: Anonymous Function terminology 486 Figure 12.3: Object Graph of a Lambda Expression 500
Figure 13.1: Delegate Invocation Sequence Diagram 517 Figure 13.2: Multicast Delegates Chained Together 518
Figure 13.3: Delegate Invocation with Exception Sequence Diagram 520
Figure 14.1: IEnumerator<T> and IEnumerator Interfaces 548 Figure 14.2: IEnumerator<T> and IEnumerator Interfaces 564 Figure 14.3: Venn Diagram of Inventor and Patent Collections 569
Figure 16.1: Generic Collection Interface Hierarchy 613 Figure 16.2: List<> Class Diagrams 618
Figure 16.3: Dictionary Class Diagrams 622
Figure 16.4: SortedList<> and SortedDictionary<> Class
Diagrams 627
Figure 16.5: Stack<T> Class Diagram 629 Figure 16.6: Queue<T> Class Diagram 629
Figure 16.7: LinkedList<T> and LinkedListNode<T> Class Diagrams 630
Figure 16.8: Sequence Diagram with yield return 640
Figure 17.1: MemberInfo Derived Classes 660
Figure 17.2: BinaryFormatter Does Not Encrypt Data 683
Figure 18.1: Clock Speeds over Time 702
Figure 18.2: CancellationTokenSource and CancellationToken Class Diagrams 721
Figure 19.1: APM Parameter Distribution 786
Figure 19.2: Delegate Parameter Distribution to BeginInvoke() and
EndInvoke() 800
Figure 20.1: Pointers Contain the Address of the Data 832
Figure 21.1: Compiling C# to Machine Code 848
xxix
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: Integer Types 32
Table 2.2: Floating-Point Types 33 Table 2.3: decimal Type 34 Table 2.4: Escape Characters 42 Table 2.5: string Static Methods 46 Table 2.6: string Methods 47
Table 2.7: Common Array Coding Errors 79
Table 3.1: Control Flow Statements 99
Table 3.2: Relational and Equality Operators 110 Table 3.3: Conditional Values for the XOR Operator 113 Table 3.4: Preprocessor Directives 139
Table 3.5: Operator Order of Precedence 146
Table 4.1: Common Namespaces 153 Table 4.2: Common Exception Types 193
Table 6.1: Why the New Modifier? 287 Table 6.2: Members of System.Object 299
Table 7.1: Comparing Abstract Classes and Interfaces 328
Table 8.1: Boxing Code in CIL 340
Table 12.1: Lambda Expression Notes and Examples 491
Table 14.1: Simpler Standard Query Operators 584
Table 14.2: Aggregate Functions on System.Linq.Enumerable 585
Table 17.1: Deserialization of a New Version Throws an Exception 685
Table 18.1: List of Available TaskContinuationOptions Enums1 712
Table 19.1: Sample Pseudocode Execution 752
Table 19.2: Interlock’s Synchronization-Related Methods 762
Table 19.3: Execution Path with ManualResetEvent Synchronization 770
Table 19.4: Concurrent Collection Classes 773
Table 19.5: Overview of the Various Timer Characteristics 779
Table 21.1: Primary C# Compilers 845
xxxi
Foreword
MARK MICHAELIS’S OVERVIEW OF THE C# language has become a standard reference for developers. In this, its third edition, programmers will find a thoughtful, well-written guide to the intricacies of one of the world’s most popular computer languages. Having laid a strong foundation in the ear-lier editions of this book, Mark adds new chapters that explain the latest features in both C# and the .NET Framework.
Two of the most important additions to the book cover the latest tools for parallel programming and the new dynamic features found in C# 4.0. The addition of dynamic features to the C# language will give developers access to late-bound languages such as Python and Ruby. Improved sup-port 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 read for C# developers who want to hone their skills and master the best and most vital parts of the C# language.
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 member, and so I woke up early to meet him. I’m glad I did. The distinct impression he made on me that morning has remained unchanged over the years.
Mark is a tall, athletic man originally from South Africa, who speaks in a clear, firm, steady voice with a slight accent that most Americans would probably find unidentifiable. He competes in Ironman triathlons and has the lean, active look that one associates with that sport. Cheerful and opti-mistic, he nevertheless has a businesslike air about him; one has the sense that he is always trying to find the best way to fit too many activities into a limited time frame.
Mark makes frequent trips to the Microsoft campus to participate in reviews of upcoming technology or to consult on a team’s plans for the future. Flying in from his home in Spokane, Washington, Mark has clearly defined agendas. He knows why he is on the campus, gives his all to the work, and looks forward to heading back home to his family in Spokane. Sometimes he finds time to fit in a quick meeting with me, and I always enjoy them. He is cheerful and energetic, and nearly always has something provocative to say about some new technology or program being devel-oped by Microsoft.
This brief portrait of Mark tells you a good deal about what you can expect from this book. It is a focused book with a clear agenda written in a cheerful, no-nonsense manner. Mark works hard to discover the core parts of the language that need to be explained and then he writes about them in the same way that he speaks: with a lucid, muscular prose that is easy to understand and totally devoid of condescension. Mark knows what his 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 para-graphs and subsections, and how to introduce and summarize a topic. He consistently finds clear, easy-to-understand ways to explain complex subjects.
Foreword xxxiii
read. Mark selects his topics with care, and explains them in the simplest possible terms. He knows what needs to be included, and what can be left out. If he wants to explore an advanced topic, he clearly sets it apart from the rest of the text. He never shows off by first parading his intellect at the expense of our desire to understand.
A centrally important part of this new edition of the book continues to be its coverage of LINQ. For many developers the declarative style of pro-gramming used by LINQ is a new technology that requires developing new habits and new ways of thinking.
C# 3.0 contained several new features that enable LINQ. A main goal of the book is to lay out these features in detail. Explaining LINQ and the technologies that enable it is no easy task, and Mark has rallied all his for-midable skills as a writer and teacher to lay this technology out for the reader in clear and easy-to-understand terms.
All the key technologies that you need to know if you want to under-stand LINQ are carefully explained in this text. These include
• Partial methods • Automatic properties • Object initializers • Collection initializers • Anonymous types
• Implicit local variables (var)
• Lambdas
• Extension methods • Expression trees
• IEnumerable<T> and IQueryable<T> • LINQ query operators
• Query expressions
in LINQ. He also explains extension methods, and the role they play in implementation of the LINQ query operators.
His coverage of C# 3.0 features culminates in his detailed explanation of query expressions. He covers the key features of query expressions such as projections, filtering, ordering, grouping, and other concepts that are cen-tral to an understanding of LINQ. He winds up his chapter on query expressions by explaining how they can be converted to the LINQ query method syntax, which is actually executed by the compiler. By the time you are done reading about query expressions you will have all the knowl-edge you need to understand LINQ and to begin using this important tech-nology in your own programs.
If you want to be a C# developer, or if you want to enhance your C# programming skills, there is no more useful tool than a well-crafted book on the subject. You are holding such a book in your hands. A text such as this can first teach you how the language works, and then live on as a ref-erence that you use when you need to quickly find answers. For develop-ers who are looking for ways to stay current on Microsoft’s technologies, this book can serve as a guide through a fascinating and rapidly changing landscape. It represents the very best and latest thought on what is fast becoming the most advanced and most important contemporary programming language.
—Charlie Calvert
Community Program Manager, Visual C#, Microsoft
xxxv
Preface
THROUGHOUT THE HISTORY of software engineering, the methodology used to write computer programs has undergone several paradigm shifts, each building on the foundation of the former by increasing code organization and decreasing complexity. This book takes you through these same para-digm shifts.
The beginning chapters take you through sequential programming structure, in which statements are written in the order in which they are executed. The problem with this model is that complexity increases expo-nentially as the requirements increase. To reduce this complexity, code blocks are moved into methods, creating a structured programming model. This allows you to call the same code block from multiple locations within a program, without duplicating code. Even with this construct, however, programs quickly become unwieldy and require further abstrac-tion. Object-oriented programming, discussed in Chapter 5, was the response. In subsequent chapters, you will learn about additional method-ologies, such as interface-based programming, LINQ (and the transforma-tion it makes to the collectransforma-tion API), and eventually rudimentary forms of declarative programming (in Chapter 17) via attributes.
This book has three main functions.
2. For readers already familiar with C#, this book provides insight into some of the more complex programming paradigms and provides in-depth coverage of the features introduced in the latest version of the language, C# 4.0 and .NET Framework 4.
3. It serves as a timeless reference, even after you gain proficiency with the language.
The key to successfully learning C# is to start coding as soon as possi-ble. Don’t wait until you are an “expert” in theory; start writing software immediately. As a believer in iterative development, I hope this book enables even a novice programmer to begin writing basic C# code by the end of Chapter 2.
A number of topics are not covered in this book. You won’t find cover-age of topics such as ASP.NET, ADO.NET, smart client development, dis-tributed programming, and so on. Although these topics are relevant to the .NET Framework, to do them justice requires books of their own. Fortu-nately, 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 rest of the series.
Target Audience for This Book
My challenge with this book was to keep advanced developers awake while not abandoning beginners by using words such as assembly, link, chain, thread, and fusion, as though the topic was more appropriate for blacksmiths than for programmers. This book’s primary audience is expe-rienced developers looking to add another language to their quiver. How-ever, I have carefully assembled this book to provide significant value to developers at all levels.
Preface xxxvii
trains you in good programming practices that will serve you throughout your programming career.
• Structured programmers: Just as it’s best to learn a foreign language through immersion, learning a computer language is most effective when you begin using it before you know all the intricacies. In this vein, this book begins with a tutorial that will be comfortable for those familiar with structured programming, and by the end of Chap-ter 4, developers in this category should feel at home writing basic control flow programs. However, the key to excellence for C# devel-opers is not memorizing syntax. To transition from simple programs to enterprise development, the C# developer must think natively in terms of objects and their relationships. To this end, Chapter 5’s Beginner Topics introduce classes and object-oriented development. The role of historically structured programming languages such as C, COBOL, 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 cate-gory. Many of you are already completely comfortable with semico-lons and curly braces. A brief glance at the code in Chapter 1 reveals that at its core, C# is similar to the C and C++ style languages that you already know.
• C# professionals: For those already versed in C#, this book provides a convenient reference for less frequently encountered syntax. Further-more, it provides answers to language details and subtleties that are seldom addressed. Most importantly, it presents the guidelines and patterns for programming robust and maintainable code. This book also aids in the task of teaching C# to others. With the emergence of C# 3.0 and C# 4.0, some of the most prominent enhancements are:
– Anonymous types (see Chapter 11) – Generics (see Chapter 11)
– Lambda statements and expressions (see Chapter 12) – Expression trees (see Chapter 12)
– Standard query operators (see Chapter 14) – Query expressions (see Chapter 15) – Dynamic programming (Chapter 17)
– Multithreaded programming with the Task Programming Library (Chapter 18)
– Parallel query processing with PLINQ – Concurrent collections (Chapter 19)
These topics are covered in detail for 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 each feature. Accompanying each concept are guidelines and best practices, ensuring that code com-piles, avoids likely pitfalls, and achieves maximum maintainability.
To improve readability, code is specially formatted and chapters are outlined using mind maps.
Code Samples
Preface xxxix
Here is a sample code listing.
Listing 1.17: Commenting Your Code
} }
The formatting is as follows.
• Comments are shown in italics.
/* Display a greeting to the console using composite formatting. */
• Keywords are shown in bold.
static void Main()
• Highlighted code calls out specific code snippets that may have changed from an earlier listing, or demonstrates the concept described in the text.
class CommentSamples {
static void Main() {
string firstName; // Variable for storing the first name
string lastName; // Variable for storing the last name
single-line comment
System.Console.WriteLine("Hey you!");
System.Console.Write /* No new line */ ( "Enter your first name: ");
firstName = System.Console.ReadLine();
System.Console.Write /* No new line */ ( "Enter your last name: ");
lastName = System.Console.ReadLine();
/* Display a greeting to the console
using composite formatting. */
System.Console.WriteLine("Your full name is {0} {1}.", firstName, lastName);
// This is the end // of the program listing
delimited comment inside statement
Highlighting can appear on an entire line or on just a few characters within a line.
System.Console.WriteLine(
• Incomplete listings contain an ellipsis to denote irrelevant code that has been omitted.
// ...
• Console output is the output from a particular listing that appears fol-lowing the listing.
• User input for the program appears in italics.
Although it might have been convenient to provide full code samples that you could copy into your own programs, doing so would detract you from learning a particular topic. Therefore, you need to modify the code samples before you can incorporate them into your programs. The core omission is error checking, such as exception handling. Also, code samples do not explicitly include using System statements. You need to assume the statement throughout all samples.
You can find sample code and bonus mateial at intelliTechture.com/ EssentialCSharp and at informit.com/msdotnetseries.
Mind Maps
Each chapter’s introduction includes a mind map, which serves as an
out-line that provides an at-a-glance reference to each chapter’s content. Here is an example (taken from Chapter 5).
System.Console.Write /* No new line */ (
"Your full name is {0} {1}.",
OUTPUT 1.4:
>HeyYou.exe Hey you!
Preface xli
The theme of each chapter appears in the mind map’s center. High-level topics spread out from the core. Mind maps allow you to absorb the flow from high-level to more detailed concepts easily, with less chance of encountering very specific knowledge that you might not be looking for.
Helpful Notes
Depending on your level of experience, special code blocks and tabs will help you navigate through the text.
• Beginner Topics provide definitions or explanations targeted specifi-cally toward entry-level programmers.
• Advanced Topics enable experienced developers to focus on the material that is most relevant to them.
• Callout notes highlight key principles in callout boxes so that readers easily recognize their significance.
• Language Contrast sidebars identify key differences between C# and its predecessors to aid those familiar with other languages.
Declaring a Property Naming Conventions Using Properties with Validation Read-Only and Write-Only Properties Access Modifiers on Getters and Setters Properties as Virtual Fields
Properties and Method Calls Not Allowed as ref or out Parameter Values
Instance Fields
Declaring an Instance Field Accessing an Instance Field Const and readonly Modifiers
Properties Static Fields Static Methods Static Constructors Static Classes Partial Classes Nested Classes Classes 2
3 Instance Methods
4
5
Static
7
Access Modifiers
9 Special Classes
Declaring and Instantiating a Class
1
8 Extension Methods
Declaring a Constructor Default Constructors Overloading Constructors Calling one Constructor Using this Finalizers
Constructors & Finalizers
How This Book Is Organized
At a high level, software engineering is about managing complexity, and it is toward this end that I have organized Essential C# 4.0 Chapters 1–4 intro-duce structured programming, which enable you to start writing simple functioning code immediately. Chapters 5–9 present the object-oriented constructs of C#. Novice readers should focus on fully understanding this section before they proceed to the more advanced topics found in the remainder of this book. Chapters 11–13 introduce additional complexity-reducing constructs, handling common patterns needed by virtually all modern programs. This leads to dynamic programming with reflection and attributes, which is used extensively for threading and interoperability in the chapters that follow.
The book ends with a chapter on the Common Language Infrastructure, which describes C# within the context of the development platform in which it operates. This chapter appears at the end because it is not C# spe-cific and it departs from the syntax and programming style in the rest of the book. However, this chapter is suitable for reading at any time, perhaps most appropriately immediately following Chapter 1.
Here is a description of each chapter (in this list, chapter numbers shown in bold indicate the presence of C# 3.0 or C# 4.0 material).
• Chapter 1—Introducing C#: After presenting the C# HelloWorld pro-gram, this chapter proceeds to dissect it. This should familiarize read-ers with the look and feel of a C# program and provide details on how to compile and debug their own programs. It also touches on the con-text of a C# program’s execution and its intermediate language. • Chapter 2—Data Types: Functioning programs manipulate data, and
this chapter introduces the primitive data types of C#. This includes coverage of two type categories, value types and reference types, along with conversion between types and support for arrays. • Chapter 3—Operators and Control Flow: To take advantage of the
iterative capabilities in a computer, you need to know how to include loops and conditional logic within your program. This chapter also covers the C# operators, data conversion, and preprocessor
directives.
Preface xliii
• Chapter 4—Methods and Parameters: This chapter investigates the details of methods and their parameters. It includes passing by value, passing by reference, and returning data via a parameter. In C# 4.0 default parameter support was added and this chapter explains how to use them.
• Chapter 5—Classes: Given the basic building blocks of a class, this chapter combines these constructs together to form fully functional types. Classes form the core of object-oriented technology by defining the template for an object.
• Chapter 6—Inheritance: Although inheritance is a programming fun-damental to many developers, C# provides some unique constructs, such as the new modifier. This chapter discusses the details of the inheritance syntax, including overriding.
• Chapter 7—Interfaces: This chapter demonstrates how interfaces are used to define the “versionable” interaction contract between classes. C# includes both explicit and implicit interface member implementa-tion, enabling an additional encapsulation level not supported by most other languages.
• Chapter 8—Value Types: Although not as prevalent as defining refer-ence types, it is sometimes necessary to define value types that behave in a fashion similar to the primitive types built into C#. This chapter describes how to define structures, while exposing the idio-syncrasies they may introduce.
• Chapter 9—Well-Formed Types: This chapter discusses more advanced type definition. It explains how to implement operators, such as + and casts, and describes how to encapsulate multiple classes into a single library. In addition, the chapter demonstrates defining namespaces and XML comments, and discusses how to design classes for garbage collection.
• Chapter 11—Generics: Generics is perhaps the core feature missing from C# 1.0. This chapter fully covers this 2.0 feature. In addition, C# 4.0 added support for covariance and contravariance—something covered in the context of generics in this chapter.
• Chapter 12—Delegates and Lambda Expressions: Delegates begin clearly distinguishing C# from its predecessors by defining patterns for han-dling events within code. This virtually eliminates the need for writ-ing routines that poll. Lambda expressions are the key concept that make C# 3.0’s LINQ possible. This chapter explains how lambda expressions build on the delegate construct by providing a more ele-gant and succinct syntax. This chapter forms the foundation for the new collection API discussed next.
• Chapter 13—Events: Encapsulated delegates, known as events, are a core construct of the Common Language Runtime. Anonymous methods, another C# 2.0 feature, are also presented here.
• Chapter 14—Collection Interfaces with Standard Query Operators: The simple and yet elegantly powerful changes introduced in C# 3.0 begin to shine in this chapter as we take a look at the extension methods of the new Enumerable class. This class makes available an entirely new collection API known as the standard query operators and discussed in detail here.
• Chapter 15—LINQ with Query Expressions: Using standard query operators alone results in some long statements that are hard to deci-pher. However, query expressions provide an alternative syntax that matches closely with SQL, as described in this chapter.
• Chapter 16—Building Custom Collections: In building custom APIs that work against business objects, it is sometimes necessary to create cus-tom collections. This chapter details how to do this, and in the process introduces contextual keywords that make custom collection build-ing easier.
Preface xlv
retrieve them via reflection. It also covers file input and output via the serialization framework within the Base Class Library. In C# 4.0 a new keyword, dynamic, was added to the language. This removed all type checking until runtime, a significant expansion of what can be done with C#.
• Chapter 18—Multithreading: Most modern programs require the use of threads to execute long-running tasks while ensuring active response to simultaneous events. As programs become more sophisti-cated, they must take additional precautions to protect data in these advanced environments. Programming multithreaded applications is complex. This chapter discusses how to work with threads and pro-vides best practices to avoid the problems that plague multithreaded applications.
• Chapter 19—Synchronization and Other Multithreading Patterns: Build-ing on the precedBuild-ing chapter, this one demonstrates some of the built-in threadbuilt-ing pattern support that can simplify the explicit control of multithreaded code.
• Chapter 20—Platform Interoperability and Unsafe Code: Given that C# is a relatively young language, far more code is written in other lan-guages than in C#. To take advantage of this preexisting code, C# supports interoperability—the calling of unmanaged code—through P/Invoke. In addition, C# provides for the use of pointers and direct memory manipulation. Although code with pointers requires special privileges to run, it provides the power to interoperate fully with tra-ditional C-based application programming interfaces.
• Chapter 21—The Common Language Infrastructure: Fundamentally, C# is the syntax that was designed as the most effective programming language on top of the underlying Common Language Infrastructure. This chapter delves into how C# programs relate to the underlying runtime and its specifications.
• Appendix A—Downloading and Installing the C# Compiler and the CLI Plat-form: This appendix provides instructions for setting up a C# compiler and the platform on which to run the code, Microsoft .NET or Mono. • Appendix B—Full Source Code Listing: In several cases, a full source code
these listings still available to the reader, this appendix includes full list-ings from Chapters 3, 11, 12, 14, and 17.
• Appendix C—Concurrent Classes from System.Collections.Concur-rent: This appendix provides overview diagrams of the concurrent collections that were added in the .NET Framework 4.
• Appendixes D-F: C# 2.0, C# 3.0, C# 4.0 Topics: These appendices pro-vide a quick reference for any C# 2.0, C# 3.0, or C# 4.0 content. They are specifically designed to help programmers quickly get up to speed on C# features.
I hope you find this book to be a great resource in establishing your C# expertise and that you continue to reference it for the more obscure areas of C# and its inner workings.
xlvii
Acknowledgments
NO BOOK CAN BE published by the author alone, and I am extremely grate-ful for the multitude of people who helped me with this one.
The order in which I thank people is not significant, except for those that come first. By far, my family has made the biggest sacrifice to allow me to complete this. Benjamin, Hanna, and Abigail often had a Daddy dis-tracted by this book, but Elisabeth suffered even more so. She was often left to take care of things, holding the family’s world together on her own. I would like to say it got easier with each edition but, alas, no; as the kids got older, life became more hectic, and without me Elisabeth was stretched to the breaking point virtually all the time. A huge sorry and ginormous Thank You!
Many technical editors reviewed each chapter in minute detail to ensure technical accuracy. I was often amazed by the subtle errors these folks still managed to catch: Paul Bramsman, Kody Brown, Ian Davis, Doug Dechow, Gerard Frantz, Thomas Heavey, Anson Horton, Brian Jones, Shane Kercheval, Angelika Langer, Eric Lippert, John Michaelis, Jason Morse, Nicholas Paldino, Jon Skeet, Michael Stokesbary, Robert Stokesbary, John Timney, and Stephen Toub.
Eric is no less than amazing. His grasp of the C# vocabulary is truly astounding and I am very appreciative of his edits, especially when he pushed for perfection in terminology. His improvements to the C# 3.0 chapters were incredibly significant, and in the second edition my only regret was that I didn’t have him review all the chapters. However, that regret is no longer. Eric painstakingly reviewed every Essential C# 4.0 chap-ter with amazing detail and precision. I am extremely grateful for his con-tribution to making this book even better than the first two editions. Thanks, Eric! I can’t imagine anyone better for the job. You deserve all the credit for raising the bar from good to great.
Like Eric and C#, there are fewer than a handful of people who know .NET multithreading as well as Stephen Toub. Accordingly, Stephen focused on the two rewritten multithreading chapters and their new focus on parallel programming. Stephen’s feedback in combination with the changes that occurred between Beta editions caused me to ask Stephen to take a second look after I updated them based on his first review—he accepted. I truly can’t imagine a better person to do the review. Thanks, Stephen! Thanks especially for putting up with me as I ramped up on the new API.
Paul and Robert were key technical reviewers for the second edition, and they painstakingly recompiled and executed each listing. This was a big effort and the errors you found were much appreciated, along with your suggestions.
Thanks to Scott Robertson at UCLA Extension for creating instructional materials for this book for university adoption.
Thanks to everyone at Addison-Wesley for their patience in working with me in spite of my frequent focus on everything else except the manu-script. Thanks to: Olivia Basegio, Sheri Cain, Curt Johnson, Joan Murray, and Brandon Prebynski.
Acknowledgments xlix
Thanks to Audrey Doyle. Anyone who can quote The Chicago Manual of Style has to be the right person to have on your team as the copy editor. The stuff she noticed and corrected made me wonder whether I am qualified to use email. Thanks especially for all the formatting help.
li
About the Author
Mark Michaelis recently started IntelliTechture, a software engineering and consulting company with high-end skills in Microsoft VSTS/TFS, Biz-Talk, SharePoint, and .NET. Mark also serves as a chief software architect and trainer for IDesign Inc.
Mark holds a BA in philosophy from the University of Illinois and an MS in computer science from the Illinois Institute of Technology. In 2007, Mark was recognized as a Microsoft Regional Director. Since 1996, he has been a Microsoft MVP for C#, Visual Studio Team System, and the Win-dows SDK. He serves on several Microsoft software design review teams, including C#, the Connected Systems Division, and VSTS. Mark speaks at developer conferences and has written numerous articles and books.
1
1
Introducing C#
IS NOW A WELL-ESTABLISHED LANGUAGE that builds on fea-tures found in its predecessor C-style languages (C, C++, and Java), making it immediately familiar to many experienced programmers.1
Part of a larger, more complex execution platform called the Common Lan-guage Infrastructure (CLI), C# is a programming lanLan-guage for building software components and applications.
This chapter introduces C# using the traditional HelloWorld program. The chapter focuses on C# syntax fundamentals, including defining an entry point into the C# program executable. This will familiarize you with
1. It has now been more than ten years since the first C# design meeting.
C#
2
3 4
5
6 1
Introducing C#
Hello, World Compiling and Runn ing
Managed Execution
C# Syntax Fundamentals
Keywords Main Statements Whitespace
Working with
Variables Declaration Assignment
Use
Console Input and Output Comm ents
Single Line Delimited
the C# syntax style and structure, and it will enable you to produce the simplest of C# programs. Prior to the discussion of C# syntax fundamen-tals is a summary of managed execution context, which explains how a C# program executes at runtime. This chapter ends with a discussion of vari-able declaration, writing and retrieving data from the console, and the basics of commenting code in C#.
Hello, World
The best way to learn a new programming language is to write code. The first example is the classic HelloWorld program. In this program, you will display some text to the screen.
Listing 1.1 shows the complete HelloWorld program; in the following sections, you will compile the code.
Listing 1.1: HelloWorld in C#2
class HelloWorld {
static void Main() {
System.Console.WriteLine("Hello. My name is Inigo Montoya."); }
}
Those experienced in programming with Java, C, or C++ will immedi-ately see similarities. Like Java, C# inherits its basic syntax from C and C++.3 Syntactic punctuation (such as semicolons and curly braces), features (such as case sensitivity), and keywords (such as class, public, and void)
2. Refer to the movie The Princess Bride if you’re confused about the Inigo Montoya references.
NOTE
C# is a case-sensitive language: Incorrect case prevents the code from compiling successfully.
Hello, World 3
are familiar to programmers experienced in these languages. Beginners and programmers from other languages will quickly find these constructs intuitive.
Compiling and Running the Application
The C# compiler allows any file extension for files containing C# source code, but .cs is typically used. After saving the source code to a file, devel-opers must compile it. (Appendix A provides instructions for installing the compiler.) Because the mechanics of the command are not part of the C# standard, the compilation command varies depending on the C# compiler implementation.
If you place Listing 1.1 into a file called HelloWorld.cs, the compilation command in Output 1.1 will work with the Microsoft .NET compiler (assuming appropriate paths to the compiler are set up).4
The exact output will vary depending on what version of the compiler you use.
Running the resultant program, HelloWorld.exe, displays the message shown in Output 1.2.
The program created by the C# compiler, HelloWorld.exe, is an assembly. Instead of creating an entire program that can be executed OUTPUT 1.1:
>csc.exe HelloWorld.cs
Microsoft (R) Visual C# 2008 Compiler version 4.0.20506.1 for Microsoft (R) .NET Framework version 4.0
Copyright (C) Microsoft Corporation. All rights reserved.
4. Compilation using the Mono compiler, an open source compiler sponsored by Novell, is virtually identical, except that the compiler name is mcs.exe rather than csc.exe. Although I would very much have liked to place instructions for each platform here, doing so detracts from the topic of introducing C#. See Appendix A for details on Mono.
OUTPUT 1.2:
>HelloWorld.exe
independently, developers can create a library of code that can be referenced by another, larger program. Libraries (or class libraries) use the filename extension .dll, which stands for Dynamic Link Library (DLL). A library is also an assembly. In other words, the output from a successful C# compile is an assembly regardless of whether it is a program or a library.
C# Syntax Fundamentals
Once you successfully compile and run the HelloWorld program, you are ready to start dissecting the code to learn its individual parts. First, con-sider the C# keywords along with the identifiers that the developer chooses.
B E G I N N E R T O P I C
Keywords
In order for the compiler to interpret the code, certain words within C# have special status and meaning. Known as keywords or reserved words, they provide the concrete syntax that the compiler uses to interpret the expressions the programmer writes. In the HelloWorld program, class, static, and void are examples of keywords.
The compiler uses the keywords to identify the structure and organiza-tion of the code. Because the compiler interprets these words with elevated significance, you can use keywords only under the specific rules identified by the language. In other words, programming languages require that developers place keywords only in certain locations. When programmers violate these rules, the compiler will issue errors.
Language Contrast: Java—Filename Must Match Class Name
C# Syntax Fundamentals 5
C# Keywords
Table 1.1 shows the C# keywords.
TABLE 1.1: C# Keywords
abstract add* alias* as
ascending* base bool break
by* byte case catch
char checked class const
continue decimal default delegate
descending* do double dynamic*
else enum equals* event
explicit extern false finally
fixed float for foreach
from* get* global* goto
group* if implicit in
int interface internal into*
is join* let* lock
long namespace new null
object on* operator orderby*
out override params partial*
private protected public readonly
ref remove* return sbyte
sealed select* set* short
sizeof stackalloc static string
struct switch this throw
true try typeof uint
[image:54.504.94.447.118.609.2]After C# 1.0, no new keywords were introduced to C#. However, some constructs in these later versions use contextual keywords, which are sig-nificant only in specific locations. Outside these designated locations, con-textual keywords have no special significance.5 By this method, all C# 1.0 code is fully compatible with the later standards.6 (Table 1.1 designates contextual keywords with a *.)
B E G I N N E R T O P I C
Identifiers
In addition to the keywords defined in C#, developers may provide their own names. Programming languages refer to these names as identifiers since they identify constructs that the programmer codes. In Listing 1.1, HelloWorld and Main are examples of identifiers. It is possible to assign a value to a variable and then refer to it later using its identifier. It is impor-tant, therefore, that the names the developer assigns are meaningful rather
ulong unchecked unsafe ushort
using value* var* virtual
void volatile where* while
yield*
* Contextual keyword
5. For example, early in the design of C# 2.0, the language designers designated yield as a keyword, and Microsoft released alpha versions of the C# 2.0 compiler, with yield as a designated keyword, to thousands of developers. However, the language designers even-tually determined that by using yield return rather than yield, they could ultimately avoid adding yield as a keyword because it would have no special significance outside its proximity to return.
6. There are some rare and unfortunate incompatibilities, such as the following:
• C# 2.0 requiring implementation of IDisposable with the using statement, rather than simply a Dispose() method
• Some rare generic expressions such as F(G<A,B>(7)); in C# 1.0, that means F((G<A), (B>7)) and in C# 2.0, that means to call generic method G<A,B> with argument 7 and pass the result to F
[image:55.504.59.414.77.173.2]C# Syntax Fundamentals 7
than arbitrary. A keen ability to select succinct and indicative names is an important characteristic of a strong programmer because the resultant code is easier to understand and reuse. In some rare cases, some identifi-ers, such as Main, can have a special meaning in the C# language.
A D V A N C E D T O P I C
Keywords
Although it is rare, keywords may be used as identifiers if they include “@” as a prefix. For example, you could name a local variable @return. Similarly (although it doesn’t conform to the casing standards of C# coding standards), it is possible to name a method @throw().
There are also four undocumented reserved keywords in the Microsoft implementation: __arglist, __makeref, __reftype, and __refvalue. These are required only in rare interop scenarios and you can ignore them for all practical purposes.
Type Definition
All code in C# appears within a type definition, and the most common type definition begins with the keyword class. A class definition is the section of code that generally begins with class identifier { ... }, as shown in Listing 1.2.
Listing 1.2: Basic Class Declaration
class HelloWorld {
... }
language. The alternative, camel casing, follows the same convention, except that the first letter is lowercase. Examples include quotient, first-Name, and theDreadPirateRoberts.
Generally, programs contain multiple types, each containing multiple methods.
Main
B E G I N N E R T O P I C
What Is a Method?
Syntactically, a method in C# is a named block of code introduced by a method declaration (for example, static void Main()) and followed by zero or more statements within curly braces. Methods perform computa-tions and/or accomputa-tions. Similar to paragraphs in written languages, methods provide a means of structuring and organizing code so that it is more read-able. More importantly, methods avoid the need to duplicate code. The method declaration introduces the method and defines the method name along with the data passed to and from the method. In Listing 1.3, Main() followed by { ... } is an example of a C# method.
The location where C# programs begin execution is the Main method, which begins with static void Main(). When you execute the program by typing HelloWorld.exe at the command console, the program starts up, resolves