Written by popular author and .NET expert Jesse Liberty, this thoroughly updated tutorial for beginning to intermediate programmers covers the latest release of Microsoft's popular C# language (C# 3.0) and the newest .NET platform for developing Windows and web applications. Our bestselling Programming C# 3.0, now in its fifth edition, is a world-class tutorial that goes well beyond the documentation otherwise available. Liberty doesn't just teach C#; he tells the complete story of the C# language and how it integrates with all of .NET programming, so that you can get started creating professional quality web and Windows applications. This book: - Provides a comprehensive tutorial in C# and .NET programming that also serves as a useful reference you'll want by your side while you're working - Covers all of the new features of the language, thoroughly integrated into every chapter, rather than tacked on at the end - Provides insight into best practices and insight into real world programming by a professional programmer who worked with C# as an independent contractor for nearly a decade before joining Microsoft as a Senior Program Manager - Every chapter in this book has been totally revised, and the entire book has been reorganized to respond to the significant changes in the language - Full coverage, from the ground up of LINQ (Language Integrated Query) and other C# 3.0 language innovations to speed up development tasks - Explains how to use C# in creating Web Applications as well as Windows Applications, using both the new Windows Presentation Foundation (WPF) and the older WinForms technology This new edition of Programming C# 3.0 is for working programmers who want to develop proficiency in Microsoft's most important language. No prior .NET experience is required for you to get started. There's no time like the present to work with C# -- and no book like this one to teach you everything you need to know. Special note to VB6 and Java programmers: if you've decided to transition to .NET, this book will take you there. Programming C# 3.0, Fifth Edition......Page 0 Table of Contents......Page 3 Preface......Page 9 What You Need to Use This Book......Page 10 Part I: The C# Language......Page 11 Part II: C# and Data......Page 12 Part IV: The CLR and the .NET Framework......Page 13 Conventions Used in This Book......Page 14 Support......Page 15 Using Code Examples......Page 16 From Jesse Liberty......Page 17 From Donald Xie......Page 18 Part I The C# Language......Page 19 The Evolution of C#......Page 21 C# Features......Page 22 The .NET Platform......Page 24 Classes, Objects, and Types......Page 25 Methods......Page 26 Comments......Page 27 Namespaces......Page 29 The Dot Operator (.)......Page 30 The using Directive......Page 31 Developing “Hello World”......Page 32 Editing “Hello World”......Page 33 Compiling and Running “Hello World”......Page 35 Using the Visual Studio 2008 Debugger......Page 36 Types......Page 39 The Built-In Types......Page 40 Choosing a built-in type......Page 41 Converting built-in types......Page 42 Variables and Constants......Page 43 Definite Assignment......Page 45 Constants......Page 46 Enumerations......Page 48 Identifiers......Page 50 Statements......Page 51 Unconditional Branching Statements......Page 52 if...else statements......Page 53 Nested if statements......Page 55 switch statements: an alternative to nested ifs......Page 56 The goto statement......Page 60 The while loop......Page 61 The for loop......Page 62 The continue and break statements......Page 65 The Assignment Operator (=)......Page 67 The modulus operator (%) to return remainders......Page 68 Calculate and reassign operators......Page 70 The prefix and postfix operators......Page 71 Relational Operators......Page 72 Operator Precedence......Page 73 The Ternary Operator......Page 76 Defining Identifiers......Page 77 #if, #elif, #else, and #endif......Page 78 Classes and Objects......Page 79 Defining Classes......Page 80 Access Modifiers......Page 83 Method Arguments......Page 84 Creating Objects......Page 85 Constructors......Page 86 Initializers......Page 88 The this Keyword......Page 91 Using Static Members......Page 93 Using Static Constructors......Page 94 Using Static Fields......Page 96 Destroying Objects......Page 97 Destructors Versus Dispose......Page 98 The using Statement......Page 100 Passing by Reference......Page 101 Overcoming Definite Assignment with out Parameters......Page 104 Overloading Methods and Constructors......Page 107 Encapsulating Data with Properties......Page 110 The get Accessor......Page 112 Property Access Modifiers......Page 113 readonly Fields......Page 114 Specialization and Generalization......Page 116 Implementing Inheritance......Page 119 Creating Polymorphic Methods......Page 120 Calling Base Class Constructors......Page 124 Versioning with the new and override Keywords......Page 125 Abstract Classes......Page 127 Limitations of Abstract......Page 129 Sealed Class......Page 130 The Root of All Types: Object......Page 131 Nesting Classes......Page 133 Using the operator Keyword......Page 136 Supporting Other .NET Languages......Page 137 The Equality Operator......Page 138 Putting Operators to Work......Page 139 Structs......Page 145 Defining Structs......Page 146 Creating Structs......Page 147 Structs As Value Types......Page 148 Defining and Implementing an Interface......Page 150 Extending Interfaces......Page 154 Combining Interfaces......Page 155 Polymorphism with Interfaces......Page 158 Interface Versus Abstract Class......Page 164 Overriding Interface Implementations......Page 165 Explicit Interface Implementation......Page 169 Selectively Exposing Interface Methods......Page 171 Member Hiding......Page 172 Arrays......Page 174 Declaring Arrays......Page 176 Understanding Default Values......Page 177 Accessing Array Elements......Page 178 The foreach Statement......Page 180 Initializing Array Elements......Page 181 The params Keyword......Page 182 Rectangular arrays......Page 183 Jagged arrays......Page 187 Array Bounds......Page 190 Array Conversions......Page 191 Sorting Arrays......Page 193 Indexers......Page 195 Indexers and Assignment......Page 199 Indexing on Other Values......Page 201 Collection Interfaces......Page 204 The IEnumerable Interface......Page 205 Constraints......Page 208 List ......Page 213 Implementing IComparable......Page 216 Implementing IComparer......Page 219 Queues......Page 224 Stacks......Page 226 Dictionaries......Page 229 IDictionary ......Page 230 Strings and Regular Expressions......Page 232 Strings......Page 233 Creating Strings......Page 234 Manipulating Strings......Page 235 Finding Substrings......Page 241 Splitting Strings......Page 244 Manipulating Dynamic Strings......Page 245 Regular Expressions......Page 247 Using Regular Expressions: Regex......Page 248 Using Regex Match Collections......Page 250 Using Regex Groups......Page 252 Using CaptureCollection......Page 255 Exceptions......Page 259 The throw Statement......Page 260 The catch Statement......Page 262 Unwinding the call stack......Page 264 Try/Catch Best Practices......Page 266 The finally Statement......Page 268 Exception Objects......Page 270 Events......Page 274 Events and Delegates......Page 275 Publish and Subscribe/Observer......Page 276 The Publishing Class: Clock......Page 280 Registering to Be Notified......Page 282 The Danger with Delegates......Page 284 The event Keyword......Page 285 Lambda Expressions......Page 289 Callback Methods......Page 290 Part II C# and Data......Page 295 Introducing LINQ......Page 297 Defining and Executing a Query......Page 298 Filtering......Page 300 Deferred Query Evaluation......Page 301 Joining......Page 303 Ordering and the var Keyword......Page 304 Grouping and the group Keyword......Page 308 Implicitly Typed Local Variables......Page 309 Extension Methods......Page 310 Defining and Using Extension Methods......Page 312 Extension Method Restrictions......Page 314 Lambda Expressions in LINQ......Page 315 XML Basics (A Quick Review)......Page 320 Elements......Page 321 Creating XML Documents......Page 322 XML Elements......Page 326 XML Attributes......Page 327 Searching in XML with XPath......Page 329 Searching for a Single Node......Page 336 Searching Using Axes......Page 337 Predicates......Page 338 XPath Functions......Page 339 Searching Using XPathNavigator......Page 340 Using XPathNodeIterator......Page 345 Using XPathExpression......Page 346 XML Serialization......Page 347 Customizing XML Serialization Using Attributes......Page 349 Runtime XML Serialization Customization......Page 351 Putting LINQ to Work......Page 355 Getting Set Up......Page 356 LINQ to SQL Fundamentals......Page 357 Using Visual Studio LINQ to SQL Designer......Page 362 Retrieving Data......Page 367 Creating Properties for Each Table......Page 368 A LINQ Query......Page 370 Updating Data Using LINQ to SQL......Page 371 Adding a Customer Record......Page 374 Modifying a Customer Record......Page 375 Deleting Relational Data......Page 376 LINQ to XML......Page 381 Relational Databases and SQL......Page 386 Tables, Records, and Columns......Page 387 Declarative Referential Integrity......Page 388 SQL......Page 389 The ADO.NET Object Model......Page 390 Data Adapter......Page 391 Getting Started with ADO.NET......Page 392 Part III Programming with C#......Page 397 Web Forms Fundamentals......Page 399 Postback versus nonpostback events......Page 401 Web Forms Life Cycle......Page 402 Creating a Web Form......Page 403 Code-Behind Files......Page 404 Adding Controls......Page 406 Data Binding......Page 409 Examining the Code......Page 413 Adding Controls and Events......Page 417 WPF in a Very Small Nutshell......Page 422 The Example Program......Page 423 Grids and Stack Panels......Page 424 Our goals......Page 427 Adding Data......Page 430 Instantiating objects declaratively......Page 431 Defining the Listbox......Page 432 The Complete XAML File......Page 433 Event Handling (Finally!)......Page 436 What Have You Learned, Dorothy?......Page 437 Creating the Application......Page 438 Creating Event Handlers......Page 441 Populating the TreeView Controls......Page 442 TreeNode objects......Page 443 Recursing through the subdirectories......Page 445 Getting the files in the directory......Page 446 Clicking the source TreeView......Page 447 Expanding a directory......Page 448 Clicking the target TreeView......Page 449 Implementing the Copy Button Event......Page 450 Getting the selected files......Page 451 Sorting the list of selected files......Page 452 Handling the Delete Button Event......Page 454 Part IV The CLR and the .NET Framework......Page 465 Attributes......Page 467 Applying attributes......Page 468 Custom Attributes......Page 469 Naming an attribute......Page 470 Using an attribute......Page 471 Viewing Metadata......Page 474 Type Discovery......Page 476 Finding all type members......Page 477 Finding type methods......Page 478 Finding particular type members......Page 479 Late Binding......Page 480 Threads and Synchronization......Page 483 Starting Threads......Page 484 Blocking Threads with Sleep......Page 487 Killing Threads......Page 488 Synchronization......Page 492 Using Interlocked......Page 495 Using Locks......Page 497 Using Monitors......Page 498 Deadlocks......Page 503 Streams......Page 505 Working with Directories......Page 506 Creating a DirectoryInfo Object......Page 507 Working with Files......Page 510 Modifying Files......Page 514 Reading and Writing Data......Page 517 Binary Files......Page 518 Buffered Streams......Page 520 Working with Text Files......Page 522 Asynchronous I/O......Page 524 Network I/O......Page 529 Creating a Network Streaming Server......Page 531 Creating a Streaming Network Client......Page 533 Handling Multiple Connections......Page 536 Asynchronous Network File Streaming......Page 540 Web Streams......Page 545 Serialization......Page 547 Working with Serialization......Page 548 Serializing the object......Page 549 Deserializing the object......Page 550 Handling Transient Data......Page 553 Isolated Storage......Page 556 Creating an ActiveX Control......Page 560 Importing a Control in .NET......Page 564 Importing a control......Page 565 Adding the control to the form......Page 566 P/Invoke......Page 569 Pointers......Page 572 C# Keywords......Page 579 Index......Page 587 Programming C# 3.0, Fifth Edition -1 Table of Contents 3 Preface 9 C# and .NET 10 About This Book 10 What You Need to Use This Book 10 How This Book Is Organized 11 Part I: The C# Language 11 Part II: C# and Data 12 Part III: Programming with C# 13 Part IV: The CLR and the .NET Framework 13 Who This Book Is For 14 Conventions Used in This Book 14 Support 15 We’d Like to Hear from You 16 Using Code Examples 16 Safari® Books Online 17 Acknowledgments 17 From Jesse Liberty 17 From Donald Xie 18 Dedications 18 From Jesse Liberty 18 From Donald Xie 18 Part I The C# Language 19 C# 3.0 and .NET 3.5 21 The Evolution of C# 21 The C# Language 22 A Tiny Bit of History 22 C# Features 22 The .NET Platform 24 Getting Started: “Hello World” 25 Classes, Objects, and Types 25 Methods 26 Comments 27 Console Applications 29 Namespaces 29 The Dot Operator (.) 30 The using Directive 31 Case Sensitivity 32 The static Keyword 32 Developing “Hello World” 32 Editing “Hello World” 33 Compiling and Running “Hello World” 35 Using the Visual Studio 2008 Debugger 36 C# Language Fundamentals 39 Types 39 The Built-In Types 40 Choosing a built-in type 41 Converting built-in types 42 Variables and Constants 43 Definite Assignment 45 Constants 46 Enumerations 48 Strings 50 Identifiers 50 Whitespace 51 Statements 51 Unconditional Branching Statements 52 Conditional Branching Statements 53 if...else statements 53 Nested if statements 55 switch statements: an alternative to nested ifs 56 Switch on string statements 60 Iteration Statements 60 The goto statement 60 The while loop 61 The do...while loop 62 The for loop 62 The foreach statement 65 The continue and break statements 65 Operators 67 The Assignment Operator (=) 67 Mathematical Operators 68 Simple arithmetical operators (+, -, *, /) 68 The modulus operator (%) to return remainders 68 Increment and Decrement Operators 70 Calculate and reassign operators 70 The prefix and postfix operators 71 Relational Operators 72 Use of Logical Operators with Conditionals 73 Operator Precedence 73 The Ternary Operator 76 Preprocessor Directives 77 Defining Identifiers 77 Undefining Identifiers 78 #if, #elif, #else, and #endif 78 Classes and Objects 79 Defining Classes 80 Access Modifiers 83 Method Arguments 84 Creating Objects 85 Constructors 86 Initializers 88 The ICloneable Interface 91 The this Keyword 91 Using Static Members 93 Invoking Static Methods 94 Using Static Constructors 94 Static Classes 96 Using Static Fields 96 Destroying Objects 97 The C# Destructor 98 Destructors Versus Dispose 98 Implementing the Close() Method 100 The using Statement 100 Passing Parameters 101 Passing by Reference 101 Overcoming Definite Assignment with out Parameters 104 Overloading Methods and Constructors 107 Encapsulating Data with Properties 110 The get Accessor 112 The set Accessor 113 Property Access Modifiers 113 readonly Fields 114 Inheritance and Polymorphism 116 Specialization and Generalization 116 Inheritance 119 Implementing Inheritance 119 Polymorphism 120 Creating Polymorphic Types 120 Creating Polymorphic Methods 120 Calling Base Class Constructors 124 Controlling Access 125 Versioning with the new and override Keywords 125 Abstract Classes 127 Limitations of Abstract 129 Sealed Class 130 The Root of All Types: Object 131 Nesting Classes 133 Operator Overloading 136 Using the operator Keyword 136 Supporting Other .NET Languages 137 Creating Useful Operators 138 Logical Pairs 138 The Equality Operator 138 Conversion Operators 139 Putting Operators to Work 139 Structs 145 Defining Structs 146 Creating Structs 147 Structs As Value Types 148 Interfaces 150 Defining and Implementing an Interface 150 Implementing More Than One Interface 154 Extending Interfaces 154 Combining Interfaces 155 Polymorphism with Interfaces 158 Interface Versus Abstract Class 164 Overriding Interface Implementations 165 Explicit Interface Implementation 169 Selectively Exposing Interface Methods 171 Member Hiding 172 Arrays, Indexers, and Collections 174 Arrays 174 Declaring Arrays 176 Understanding Default Values 177 Accessing Array Elements 178 The foreach Statement 180 Initializing Array Elements 181 The params Keyword 182 Multidimensional Arrays 183 Rectangular arrays 183 Jagged arrays 187 Array Bounds 190 Array Conversions 191 Sorting Arrays 193 Indexers 195 Indexers and Assignment 199 Indexing on Other Values 201 Collection Interfaces 204 The IEnumerable Interface 205 Constraints 208 List 213 Implementing IComparable 216 Implementing IComparer 219 Queues 224 Stacks 226 Dictionaries 229 IDictionary 230 Strings and Regular Expressions 232 Strings 233 Creating Strings 234 The ToString() Method 235 Manipulating Strings 235 Finding Substrings 241 Splitting Strings 244 Manipulating Dynamic Strings 245 Regular Expressions 247 Using Regular Expressions: Regex 248 Using Regex Match Collections 250 Using Regex Groups 252 Using CaptureCollection 255 Exceptions 259 Throwing and Catching Exceptions 260 The throw Statement 260 The catch Statement 262 Taking corrective action 264 Unwinding the call stack 264 Try/Catch Best Practices 266 The finally Statement 268 Exception Objects 270 Delegates and Events 274 Events 274 Events and Delegates 275 Indirect Invocation 276 Publish and Subscribe/Observer 276 The Publishing Class: Clock 280 Registering to Be Notified 282 Sequence of Events 284 The Danger with Delegates 284 The event Keyword 285 Anonymous Methods 289 Lambda Expressions 289 Callback Methods 290 Part II C# and Data 295 Introducing LINQ 297 Defining and Executing a Query 298 Creating the Query 300 The from clause 300 Filtering 300 Projection (or select) 301 Deferred Query Evaluation 301 LINQ and C# 303 Joining 303 Ordering and the var Keyword 304 Grouping and the group Keyword 308 Anonymous Types 309 Implicitly Typed Local Variables 309 Extension Methods 310 Defining and Using Extension Methods 312 Extension Method Restrictions 314 Lambda Expressions in LINQ 315 Working with XML 320 XML Basics (A Quick Review) 320 Elements 321 XHTML 322 X Stands for eXtensible 322 Creating XML Documents 322 XML Elements 326 XML Attributes 327 Searching in XML with XPath 329 Searching for a Single Node 336 Searching Using Axes 337 Predicates 338 XPath Functions 339 Searching Using XPathNavigator 340 Using XPathNodeIterator 345 Using XPathExpression 346 XML Serialization 347 Customizing XML Serialization Using Attributes 349 Runtime XML Serialization Customization 351 Putting LINQ to Work 355 Getting Set Up 356 LINQ to SQL Fundamentals 357 Using Visual Studio LINQ to SQL Designer 362 Retrieving Data 367 Creating Properties for Each Table 368 A LINQ Query 370 Updating Data Using LINQ to SQL 371 Adding a Customer Record 374 Modifying a Customer Record 375 Deleting Relational Data 376 LINQ to XML 381 ADO.NET and Relational Databases 386 Relational Databases and SQL 386 Tables, Records, and Columns 387 Normalization 388 Declarative Referential Integrity 388 SQL 389 The ADO.NET Object Model 390 DataTables and DataColumns 391 DataRelations 391 Rows 391 Data Adapter 391 DBCommand and DBConnection 392 DataReader 392 Getting Started with ADO.NET 392 Part III Programming with C# 397 Programming ASP.NET Applications 399 Web Forms Fundamentals 399 Web Forms Events 401 Postback versus nonpostback events 401 State 402 Web Forms Life Cycle 402 Creating a Web Form 403 Code-Behind Files 404 Adding Controls 406 Server Controls 409 Data Binding 409 Examining the Code 413 Adding Controls and Events 417 Programming WPF Applications 422 WPF in a Very Small Nutshell 422 Creating a WPF Example 423 The Example Program 423 Building the Application 424 Grids and Stack Panels 424 Sucking on a Fire Hose 427 Our goals 427 Adding Data 430 Instantiating objects declaratively 431 Using the Data in the XAML 432 Defining the Listbox 432 The Complete XAML File 433 Event Handling (Finally!) 436 What Have You Learned, Dorothy? 437 Programming Windows Forms Applications 438 Creating the Application 438 Creating Event Handlers 441 Populating the TreeView Controls 442 TreeNode objects 443 Recursing through the subdirectories 445 Getting the files in the directory 446 Handling TreeView Events 447 Clicking the source TreeView 447 Expanding a directory 448 Clicking the target TreeView 449 Handling the Clear button event 450 Implementing the Copy Button Event 450 Getting the selected files 451 Sorting the list of selected files 452 Handling the Delete Button Event 454 Part IV The CLR and the .NET Framework 465 Attributes and Reflection 467 Attributes 467 Types of Attributes 468 Attribute targets 468 Applying attributes 468 Custom Attributes 469 Declaring an attribute 470 Naming an attribute 470 Constructing an attribute 471 Using an attribute 471 Reflection 474 Viewing Metadata 474 Type Discovery 476 Reflecting on a Type 477 Finding all type members 477 Finding type methods 478 Finding particular type members 479 Late Binding 480 Threads and Synchronization 483 Threads 484 Starting Threads 484 Joining Threads 487 Blocking Threads with Sleep 487 Killing Threads 488 Synchronization 492 Using Interlocked 495 Using Locks 497 Using Monitors 498 Race Conditions and Deadlocks 503 Race Conditions 503 Deadlocks 503 Streams 505 Files and Directories 506 Working with Directories 506 Creating a DirectoryInfo Object 507 Working with Files 510 Modifying Files 514 Reading and Writing Data 517 Binary Files 518 Buffered Streams 520 Working with Text Files 522 Asynchronous I/O 524 Network I/O 529 Creating a Network Streaming Server 531 Creating a Streaming Network Client 533 Handling Multiple Connections 536 Asynchronous Network File Streaming 540 Web Streams 545 Serialization 547 Using a Formatter 548 Working with Serialization 548 Serializing the object 549 Deserializing the object 550 Handling Transient Data 553 Isolated Storage 556 Programming .NET and COM 560 Importing ActiveX Controls 560 Creating an ActiveX Control 560 Importing a Control in .NET 564 Importing a control 565 Manually importing the control 566 Adding the control to the form 566 P/Invoke 569 Pointers 572 C# Keywords 579 Index 587