Pro C# 2010 and the .NET 4 Platform Fifth Edition ■ ■ ■ Andrew Troelsen Pro C# 2010 and the .NET 4 Platform, Fifth Edition Copyright © 2010 by Andrew Troelsen All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 978-1-4302-2549-2 ISBN-13 (electronic): 978-1-4302-2550-8 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. President and Publisher: Paul Manning Lead Editor: Ewan Buckingham Technical Reviewer: Andy Olsen Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh Coordinating Editor: Debra Kelly Copy Editors: Patrick Meader, Katie Stence, and Sharon Terdeman Compositor: folio 2 Indexer: Potomac Indexers Artist: April Milne Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail [email protected], or visit www.springeronline.com. For information on translations, please e-mail [email protected], or visit www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. The source code for this book is available to readers at www.apress.com. Contents at a Glance Contents...................................................................................................................viii About the Author.....................................................................................................xxv About the Technical Reviewer...............................................................................xxvi Acknowledgments................................................................................................xxvii Introduction.........................................................................................................xxviii ■ ■ ■ Part 1: Introducing C# and the .NET Platform.................................................1 ■ Chapter 1: The Philosophy of .NET..........................................................................3 ■ Chapter 2: Building C# Applications.....................................................................41 ■ ■ ■ Part 2: Core C# Programming Constructs ....................................................71 ■ Chapter 3: Core C# Programming Constructs, Part I............................................73 ■ Chapter 4: Core C# Programming Constructs, Part II.........................................125 ■ Chapter 5: Defining Encapsulated Class Types...................................................167 ■ Chapter 6: Understanding Inheritance and Polymorphism.................................219 ■ Chapter 7: Understanding Structured Exception Handling.................................259 ■ Chapter 8: Understanding Object Lifetime..........................................................289 ■ ■ ■ Part 3: Advanced C# Programming Constructs..........................................319 ■ Chapter 9: Working with Interfaces....................................................................321 ■ Chapter 10: Understanding Generics..................................................................361 v ■ CONTENTS AT A GLANCE ■ Chapter 11: Delegates, Events, and Lambdas.....................................................397 ■ Chapter 12: Advanced C# Language Features....................................................439 ■ Chapter 13: LINQ to Objects................................................................................489 ■ ■ ■ Part 4: Programming with .NET Assemblies...............................................523 ■ Chapter 14: Configuring .NET Assemblies..........................................................525 ■ Chapter 15: Type Reflection, Late Binding, and Attribute-Based Programming......581 ■ Chapter 16: Processes, AppDomains, and Object Contexts................................625 ■ Chapter 17: Understanding CIL and the Role of Dynamic Assemblies................653 ■ Chapter 18: Dynamic Types and the Dynamic Language Runtime.....................701 ■ ■ ■ Part 5: Introducing the .NET Base Class Libraries......................................725 ■ Chapter 19: Multithreaded and Parallel Programming.......................................727 ■ Chapter 20: File I/O and Object Serialization......................................................775 ■ Chapter 21: ADO.NET Part I: The Connected Layer..............................................825 ■ Chapter 22: ADO.NET Part II: The Disconnected Layer........................................885 ■ Chapter 23: ADO.NET Part III: The Entity Framework.........................................951 ■ Chapter 24: Introducing LINQ to XML.................................................................993 ■ Chapter 25: Introducing Windows Communication Foundation.......................1013 ■ Chapter 26: Introducing Windows Workflow Foundation 4.0...........................1077 ■ ■ ■ Part 6: Building Desktop User Interfaces with WPF .................................1115 ■ Chapter 27: Introducing Windows Presentation Foundation and XAML...........1117 ■ Chapter 28: Programming with WPF Controls..................................................1179 ■ Chapter 29: WPF Graphics Rendering Services................................................1245 ■ Chapter 30: WPF Resources, Animations, and Styles.......................................1285 ■ Chapter 31: WPF Control Templates and UserControls.....................................1325 vi ■ CONTENTS AT A GLANCE ■ ■ ■ Part 7: Building Web Applications with ASP.NET......................................1377 ■ Chapter 32: Building ASP.NET Web Pages........................................................1379 ■ Chapter 33: ASP.NET Web Controls, Master Pages and Themes......................1429 ■ Chapter 34: ASP.NET State Management Techniques.......................................1473 ■ Appendix A: Programming with Windows Forms.............................................1511 ■ Appendix B: Platform-Independent .NET Development with Mono...................1561 ■ Index.................................................................................................................1583 vii ■ CONTENTS Contents About the Author.....................................................................................................xxv About the Technical Reviewer...............................................................................xxvi Acknowledgments................................................................................................xxvii Introduction.........................................................................................................xxviii ■ ■ ■ Part 1: Introducing C# and the .NET Platform.................................................1 ■ Chapter 1: The Philosophy of .NET..........................................................................3 Understanding the Previous State of Affairs......................................................................3 The .NET Solution..............................................................................................................6 Introducing the Building Blocks of the .NET Platform (the CLR, CTS, and CLS).................7 Additional .NET-Aware Programming Languages............................................................10 An Overview of .NET Assemblies.....................................................................................12 Understanding the Common Type System.......................................................................19 Understanding the Common Language Specification......................................................23 Understanding the Common Language Runtime.............................................................25 The Assembly/Namespace/Type Distinction...................................................................27 Exploring an Assembly Using ildasm.exe........................................................................33 Exploring an Assembly Using Reflector...........................................................................35 Deploying the .NET Runtime............................................................................................36 viii ■ CONTENTS The Platform-Independent Nature of .NET.......................................................................37 Summary.........................................................................................................................39 ■ Chapter 2: Building C# Applications.....................................................................41 The Role of the .NET Framework 4.0 SDK.......................................................................41 Building C# Applications Using csc.exe...........................................................................42 Building .NET Applications Using Notepad++.................................................................49 Building .NET Applications Using SharpDevelop..............................................................50 Building .NET Applications Using Visual C# 2010 Express..............................................53 Building .NET Applications Using Visual Studio 2010......................................................54 Summary.........................................................................................................................69 ■ ■ ■ Part 2: Core C# Programming Constructs ....................................................71 ■ Chapter 3: Core C# Programming Constructs, Part I............................................73 The Anatomy of a Simple C# Program.............................................................................73 An Interesting Aside: Some Additional Members of the System.Environment Class.......79 The System.Console Class...............................................................................................81 System Data Types and C# Shorthand Notation..............................................................86 Working with String Data.................................................................................................97 Narrowing and Widening Data Type Conversions..........................................................106 Understanding Implicitly Typed Local Variables............................................................112 C# Iteration Constructs..................................................................................................117 Decision Constructs and the Relational/Equality Operators..........................................119 Summary.......................................................................................................................122 ■ Chapter 4: Core C# Programming Constructs, Part II.........................................125 Methods and Parameter Modifiers................................................................................125 Understanding C# Arrays...............................................................................................137 Understanding the Enum Type.......................................................................................144 ix ■ CONTENTS Understanding the Structure Type.................................................................................151 Understanding Value Types and Reference Types.........................................................154 Understanding C# Nullable Types..................................................................................162 Summary.......................................................................................................................165 ■ Chapter 5: Defining Encapsulated Class Types...................................................167 Introducing the C# Class Type.......................................................................................167 Understanding Constructors..........................................................................................170 The Role of the this Keyword.........................................................................................174 Understanding the static Keyword.................................................................................181 Defining the Pillars of OOP.............................................................................................188 C# Access Modifiers......................................................................................................192 The First Pillar: C#’s Encapsulation Services.................................................................194 Understanding Automatic Properties.............................................................................206 Understanding Object Initializer Syntax.........................................................................210 Working with Constant Field Data.................................................................................214 Understanding Partial Types..........................................................................................217 Summary.......................................................................................................................218 ■ Chapter 6: Understanding Inheritance and Polymorphism.................................219 The Basic Mechanics of Inheritance..............................................................................219 Revising Visual Studio Class Diagrams.........................................................................224 The Second Pillar of OOP: The Details of Inheritance....................................................226 Programming for Containment/Delegation....................................................................232 The Third Pillar of OOP: C#’s Polymorphic Support.......................................................235 Understanding Base Class/Derived Class Casting Rules...............................................247 The Master Parent Class: System.Object.......................................................................250 Summary.......................................................................................................................258 x ■ CONTENTS ■ Chapter 7: Understanding Structured Exception Handling.................................259 Ode to Errors, Bugs, and Exceptions.............................................................................259 The Role of .NET Exception Handling.............................................................................260 The Simplest Possible Example.....................................................................................263 Configuring the State of an Exception...........................................................................267 System-Level Exceptions (System.SystemException)...................................................272 Application-Level Exceptions (System.ApplicationException).......................................273 Processing Multiple Exceptions.....................................................................................277 Who Is Throwing What?.................................................................................................282 The Result of Unhandled Exceptions.............................................................................283 Debugging Unhandled Exceptions Using Visual Studio.................................................284 A Brief Word Regarding Corrupted State Exceptions (CSE)...........................................285 Summary.......................................................................................................................287 ■ Chapter 8: Understanding Object Lifetime..........................................................289 Classes, Objects, and References..................................................................................289 The Basics of Object Lifetime........................................................................................291 The Role of Application Roots........................................................................................294 Understanding Object Generations................................................................................296 Concurrent Garbage Collection under .NET 1.0 - 3.5.....................................................297 Background Garbage Collection under .NET 4.0............................................................297 The System.GC Type......................................................................................................298 Building Finalizable Objects...........................................................................................302 Building Disposable Objects..........................................................................................305 Building Finalizable and Disposable Types....................................................................309 Understanding Lazy Object Instantiation.......................................................................313 Summary.......................................................................................................................316 xi ■ CONTENTS ■ ■ ■ Part 3: Advanced C# Programming Constructs..........................................319 ■ Chapter 9: Working with Interfaces....................................................................321 Understanding Interface Types......................................................................................321 Defining Custom Interfaces...........................................................................................325 Implementing an Interface.............................................................................................327 Invoking Interface Members at the Object Level...........................................................329 Interfaces As Parameters..............................................................................................331 Interfaces As Return Values...........................................................................................333 Arrays of Interface Types...............................................................................................334 Implementing Interfaces Using Visual Studio 2010.......................................................335 Resolving Name Clashes via Explicit Interface Implementation....................................336 Designing Interface Hierarchies....................................................................................339 Building Enumerable Types (IEnumerable and IEnumerator)........................................343 Building Cloneable Objects (ICloneable)........................................................................349 Building Comparable Objects (IComparable).................................................................354 Summary.......................................................................................................................359 ■ Chapter 10: Understanding Generics..................................................................361 The Issues with Non-Generic Collections......................................................................361 The Role of Generic Type Parameters...........................................................................371 The System.Collections.Generic Namespace................................................................376 Creating Custom Generic Methods................................................................................385 Creating Custom Generic Structures and Classes.........................................................388 Constraining Type Parameters......................................................................................392 Summary.......................................................................................................................395 ■ Chapter 11: Delegates, Events, and Lambdas.....................................................397 Understanding the .NET Delegate Type.........................................................................397 xii