Visual C#2010从入门到精通(Visual CSharp 2010 Step by Step)

Table of Contents Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix Who This Book Is For . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xix Finding Your Best Starting Point in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . xx Conventions and Features in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxi Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxi Other Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxii Prerelease Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxii Hardware and Software Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxii Code Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxiii Installing the Code Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxiii Using the Code Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxiii Uninstalling the Code Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxix Find Additional Content Online . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxx Support for This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxx Questions and Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxx Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 Welcome .to .C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Beginning Programming with the Visual Studio 2010 Environment . . . . . . . . . . 3 Writing Your First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Using Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Creating a Graphical Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Chapter 1 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Working .with .Variables, .Operators, .and .Expressions . . . . . . . . . . . . . 27 Understanding Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Using Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Identifying Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Using Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Naming Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Declaring Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Working with Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Unassigned Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Displaying Primitive Data Type Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Using Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Operators and Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Examining Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Controlling Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Using Associativity to Evaluate Expressions . . . . . . . . . . . . . . . . . . . . . . . . 42 Associativity and the Assignment Operator . . . . . . . . . . . . . . . . . . . . . . . . 42 Incrementing and Decrementing Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Prefix and Postfix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Declaring Implicitly Typed Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Chapter 2 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Writing .Methods .and .Applying .Scope . . . . . . . . . . . . . . . . . . . . . . . . . 47 Creating Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Declaring a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 Returning Data from a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Calling Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Microsoft® Visual C#® 2010 Step by Step John Sharp PUBLISHED BY Microsoft Press A Division of Microsoft Corporation One Microsoft Way Redmond, Washington 98052-6399 Copyright © 2010 by John Sharp All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the publisher. Library of Congress Control Number: 2009939912 Printed and bound in the United States of America. 1 2 3 4 5 6 7 8 9 QWT 5 4 3 2 1 0 Distributed in Canada by H.B. Fenn and Company Ltd. A CIP catalogue record for this book is available from the British Library. Microsoft Press books are available through booksellers and distributors worldwide. For further infor­mation about international editions, contact your local Microsoft Corporation office or contact Microsoft Press International directly at fax (425) 936-7329. Visit our Web site at www.microsoft.com/mspress. Send comments to mspinput@microsoft.com. Microsoft, Microsoft Press, Excel, IntelliSense, Internet Explorer, Jscript, MS, MSDN, SQL Server, Visual Basic, Visual C#, Visual C++, Visual Studio, Win32, Windows, and Windows Vista are either registered trademarks or trademarks of the Microsoft group of companies. Other product and company names mentioned herein may be the trademarks of their respective owners. The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious. No association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred. This book expresses the author’s views and opinions. The information contained in this book is provided without any express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers, or distributors will be held liable for any damages caused or alleged to be caused either directly or indirectly by this book. Acquisitions Editor: Ben Ryan Developmental Editor: Devon Musgrave Project Editor: Rosemary Caperton Editorial Production: Waypoint Press, www.waypointpress.com Technical Reviewer: Per Blomqvist; Technical Review services provided by Content Master, a member of CM Group, Ltd. Cover: Tom Draper Design Body Part No. X16-81630 . iii Contents at a Glance Part I . Introducing .Microsoft .Visual .C# .and .Microsoft . Visual .Studio .2010 . 1 Welcome to C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 . 2 Working with Variables, Operators, and Expressions . . . . . . . . . 27 . 3 Writing Methods and Applying Scope . . . . . . . . . . . . . . . . . . . . . 47 . 4 Using Decision Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 . 5 Using Compound Assignment and Iteration Statements . . . . . . 91 . 6 Managing Errors and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . 109 Part II . Understanding .the .C# .Language . 7 Creating and Managing Classes and Objects . . . . . . . . . . . . . . . 129 . 8 Understanding Values and References . . . . . . . . . . . . . . . . . . . . 151 . 9 Creating Value Types with Enumerations and Structures . . . . . 173 . 10 Using Arrays and Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 . 11 Understanding Parameter Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 219 . 12 Working with Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 . 13 Creating Interfaces and Defining Abstract Classes . . . . . . . . . . 253 . 14 Using Garbage Collection and Resource Management . . . . . . . 279 Part III . Creating .Components . 15 Implementing Properties to Access Fields . . . . . . . . . . . . . . . . . 295 . 16 Using Indexers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 . 17 Interrupting Program Flow and Handling Events . . . . . . . . . . . 329 . 18 Introducing Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 . 19 Enumerating Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 . 20 Querying In-Memory Data by Using Query Expressions . . . . . 395 . 21 Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 iv Contents at a Glance Part IV .Building .Windows .Presentation .Foundation . Applications . 22 Introducing Windows Presentation Foundation . . . . . . . . . . . . 443 . 23 Gathering User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477 . 24 Performing Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509 Part V . Managing .Data . 25 Querying Information in a Database . . . . . . . . . . . . . . . . . . . . . . 535 . 26 Displaying and Editing Data by Using the Entity Framework and Data Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565 Part VI .Building .Professional .Solutions .with . Visual .Studio .2010 . 27 Introducing the Task Parallel Library . . . . . . . . . . . . . . . . . . . . . . 599 . 28 Performing Parallel Data Access . . . . . . . . . . . . . . . . . . . . . . . . . . 649 . 29 Creating and Using a Web Service . . . . . . . . . . . . . . . . . . . . . . . . 683 Appendix . Interoperating with Dynamic Languages . . . . . . . . . . . . . . . . . . 717 . v Table of Contents Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xix Part I . Introducing .Microsoft .Visual .C# .and .Microsoft . Visual .Studio .2010 . 1 Welcome to C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Beginning Programming with the Visual Studio 2010 Environment . . . . . . . . . . 3 Writing Your First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Using Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Creating a Graphical Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Chapter 1 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 . 2 Working with Variables, Operators, and Expressions . . . . . . . . . 27 Understanding Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Using Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Identifying Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Using Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Naming Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Declaring Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Working with Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Unassigned Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Displaying Primitive Data Type Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Using Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Operators and Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Examining Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Controlling Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Using Associativity to Evaluate Expressions . . . . . . . . . . . . . . . . . . . . . . . . 42 Associativity and the Assignment Operator . . . . . . . . . . . . . . . . . . . . . . . . 42 Microsoft is interested in hearing your feedback so we can continually improve our books and learning resources for you. To participate in a brief online survey, please visit: www.microsoft.com/learning/booksurvey/ What do you think of this book? We want to hear from you! vi Table of Contents Incrementing and Decrementing Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Prefix and Postfix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Declaring Implicitly Typed Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Chapter 2 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 . 3 Writing Methods and Applying Scope . . . . . . . . . . . . . . . . . . . . . 47 Creating Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Declaring a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 Returning Data from a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Calling Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Specifying the Method Call Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Applying Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Defining Local Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Defining Class Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Overloading Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Writing Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Using Optional Parameters and Named Arguments . . . . . . . . . . . . . . . . . . . . . . 64 Defining Optional Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 Passing Named Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Resolving Ambiguities with Optional Parameters and Named Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Chapter 3 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 . 4 Using Decision Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Declaring Boolean Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Using Boolean Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 Understanding Equality and Relational Operators . . . . . . . . . . . . . . . . . . 74 Understanding Conditional Logical Operators . . . . . . . . . . . . . . . . . . . . . . 75 Short-Circuiting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 Summarizing Operator Precedence and Associativity . . . . . . . . . . . . . . . 76 Using if Statements to Make Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Understanding if Statement Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Using Blocks to Group Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 Cascading if Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 Using switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 Understanding switch Statement Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Following the switch Statement Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Chapter 4 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 Table of Contents vii . 5 Using Compound Assignment and Iteration Statements . . . . . . 91 Using Compound Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Writing while Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Writing for Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 Understanding for Statement Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Writing do Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 Chapter 5 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 . 6 Managing Errors and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . 109 Coping with Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Trying Code and Catching Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 Unhandled Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Using Multiple catch Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Catching Multiple Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 Using Checked and Unchecked Integer Arithmetic . . . . . . . . . . . . . . . . . . . . . . 118 Writing Checked Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Writing Checked Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Throwing Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Using a finally Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 Chapter 6 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 Part II . Understanding .the .C# .Language . 7 Creating and Managing Classes and Objects . . . . . . . . . . . . . . . 129 Understanding Classification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 The Purpose of Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 Defining and Using a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 Controlling Accessibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Working with Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 Overloading Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .134 Understanding static Methods and Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 Creating a Shared Field . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Creating a static Field by Using the const Keyword . . . . . . . . . . . . . . . . .144 Static Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .144 Anonymous Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Chapter 7 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 viii Table of Contents . 8 Understanding Values and References . . . . . . . . . . . . . . . . . . . . 151 Copying Value Type Variables and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 Understanding Null Values and Nullable Types . . . . . . . . . . . . . . . . . . . . . . . . . 156 Using Nullable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 Understanding the Properties of Nullable Types . . . . . . . . . . . . . . . . . . . 158 Using ref and out Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Creating ref Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Creating out Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 How Computer Memory Is Organized . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 Using the Stack and the Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .164 The System.Object Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 Boxing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 Unboxing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 Casting Data Safely . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 The is Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 The as Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 Chapter 8 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 . 9 Creating Value Types with Enumerations and Structures . . . . . 173 Working with Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 Declaring an Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 Using an Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 Choosing Enumeration Literal Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 Choosing an Enumeration’s Underlying Type . . . . . . . . . . . . . . . . . . . . . . 176 Working with Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 Declaring a Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .180 Understanding Structure and Class Differences . . . . . . . . . . . . . . . . . . . . 181 Declaring Structure Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 Understanding Structure Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 Copying Structure Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 Chapter 9 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .190 . 10 Using Arrays and Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 What Is an Array? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 Declaring Array Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 Creating an Array Instance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 Initializing Array Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 Table of Contents ix Creating an Implicitly Typed Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .194 Accessing an Individual Array Element . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 Iterating Through an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 Copying Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 Using Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Using Arrays to Play Cards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 What Are Collection Classes? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .206 The ArrayList Collection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .208 The Queue Collection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 The Stack Collection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 The Hashtable Collection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 The SortedList Collection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 Using Collection Initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 Comparing Arrays and Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 Using Collection Classes to Play Cards . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 Chapter 10 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 . 11 Understanding Parameter Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 219 Using Array Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 Declaring a params Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 Using params object[ ] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 Using a params Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 Comparing Parameters Arrays and Optional Parameters . . . . . . . . . . . . . . . . . 226 Chapter 11 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 . 12 Working with Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 What Is Inheritance? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 Using Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 Calling Base Class Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 Assigning Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 Declaring new Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 Declaring Virtual Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 Declaring override Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 Understanding protected Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 Understanding Extension Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 Chapter 12 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 x Table of Contents . 13 Creating Interfaces and Defining Abstract Classes . . . . . . . . . . 253 Understanding Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 Defining an Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 Implementing an Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 Referencing a Class Through Its Interface . . . . . . . . . . . . . . . . . . . . . . . . . 256 Working with Multiple Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 Explicitly Implementing an Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 Interface Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 Defining and Using Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 Abstract Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 Abstract Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Sealed Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 Sealed Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 Implementing and Using an Abstract Class . . . . . . . . . . . . . . . . . . . . . . . . 272 Chapter 13 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 . 14 Using Garbage Collection and Resource Management . . . . . . . 279 The Life and Times of an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 Writing Destructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 Why Use the Garbage Collector? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 How Does the Garbage Collector Work? . . . . . . . . . . . . . . . . . . . . . . . . . . 283 Recommendations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .284 Resource Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .284 Disposal Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 Exception-Safe Disposal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 The using Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 Calling the Dispose Method from a Destructor . . . . . . . . . . . . . . . . . . . . 288 Implementing Exception-Safe Disposal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 Chapter 14 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292 Part III . Creating .Components . 15 Implementing Properties to Access Fields . . . . . . . . . . . . . . . . . 295 Implementing Encapsulation by Using Methods . . . . . . . . . . . . . . . . . . . . . . . .296 What Are Properties? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 Using Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .299 Read-Only Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .300 Table of Contents xi Write-Only Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .300 Property Accessibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 Understanding the Property Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 Declaring Interface Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .304 Using Properties in a Windows Application . . . . . . . . . . . . . . . . . . . . . . . 305 Generating Automatic Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 Initializing Objects by Using Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .308 Chapter 15 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 . 16 Using Indexers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 What Is an Indexer? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 An Example That Doesn’t Use Indexers . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 The Same Example Using Indexers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 Understanding Indexer Accessors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 Comparing Indexers and Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 Indexers in Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 Using Indexers in a Windows Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 Chapter 16 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 . 17 Interrupting Program Flow and Handling Events . . . . . . . . . . . 329 Declaring and Using Delegates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 The Automated Factory Scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 Implementing the Factory Without Using Delegates . . . . . . . . . . . . . . . 330 Implementing the Factory by Using a Delegate . . . . . . . . . . . . . . . . . . . . 331 Using Delegates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 Lambda Expressions and Delegates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 Creating a Method Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 Using a Lambda Expression as an Adapter . . . . . . . . . . . . . . . . . . . . . . . . 339 The Form of Lambda Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .340 Enabling Notifications with Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 Declaring an Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 Subscribing to an Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 Unsubscribing from an Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .344 Raising an Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .344 Understanding WPF User Interface Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 Using Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .346 Chapter 17 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 xii Table of Contents . 18 Introducing Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 The Problem with objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 The Generics Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 Generics vs . Generalized Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 Generics and Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 Creating a Generic Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 The Theory of Binary Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 Building a Binary Tree Class by Using Generics . . . . . . . . . . . . . . . . . . . . 361 Creating a Generic Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 Defining a Generic Method to Build a Binary Tree . . . . . . . . . . . . . . . . . 371 Variance and Generic Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373 Covariant Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375 Contravariant Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 Chapter 18 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 . 19 Enumerating Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 Enumerating the Elements in a Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 Manually Implementing an Enumerator . . . . . . . . . . . . . . . . . . . . . . . . . . 383 Implementing the IEnumerable Interface . . . . . . . . . . . . . . . . . . . . . . . . . 387 Implementing an Enumerator by Using an Iterator . . . . . . . . . . . . . . . . . . . . . . 389 A Simple Iterator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389 Defining an Enumerator for the Tree Class by Using an Iterator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 Chapter 19 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .394 . 20 Querying In-Memory Data by Using Query Expressions . . . . . 395 What Is Language Integrated Query? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 Using LINQ in a C# Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396 Selecting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 Filtering Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .400 Ordering, Grouping, and Aggregating Data . . . . . . . . . . . . . . . . . . . . . . . 401 Joining Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .404 Using Query Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .405 Querying Data in Tree Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 407 LINQ and Deferred Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412 Chapter 20 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 Table of Contents xiii . 21 Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 Understanding Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 Operator Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420 Overloaded Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420 Creating Symmetric Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422 Understanding Compound Assignment Evaluation . . . . . . . . . . . . . . . . . . . . . . 424 Declaring Increment and Decrement Operators . . . . . . . . . . . . . . . . . . . . . . . . 425 Comparing Operators in Structures and Classes . . . . . . . . . . . . . . . . . . . . . . . . 426 Defining Operator Pairs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426 Implementing Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427 Understanding Conversion Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434 Providing Built-in Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434 Implementing User-Defined Conversion Operators . . . . . . . . . . . . . . . . 435 Creating Symmetric Operators, Revisited . . . . . . . . . . . . . . . . . . . . . . . . . 436 Writing Conversion Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437 Chapter 21 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .440 Part IV .Building .Windows .Presentation .Foundation . Applications . 22 Introducing Windows Presentation Foundation . . . . . . . . . . . . 443 Creating a WPF Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .443 Building the WPF Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .444 Adding Controls to the Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458 Using WPF Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458 Changing Properties Dynamically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .466 Handling Events in a WPF Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470 Processing Events in Windows Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471 Chapter 22 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476 . 23 Gathering User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477 Menu Guidelines and Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477 Menus and Menu Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478 Creating a Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478 Handling Menu Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .484 Shortcut Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491 Creating Shortcut Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491 xiv Table of Contents Windows Common Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 Using the SaveFileDialog Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 Improving Responsiveness in a WPF Application . . . . . . . . . . . . . . . . . . . . . . . . 498 Chapter 23 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .508 . 24 Performing Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509 Validating Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .509 Strategies for Validating User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .509 An Example—Order Tickets for Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510 Performing Validation by Using Data Binding . . . . . . . . . . . . . . . . . . . . . 511 Changing the Point at Which Validation Occurs . . . . . . . . . . . . . . . . . . . 527 Chapter 24 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531 Part V . Managing .Data . 25 Querying Information in a Database . . . . . . . . . . . . . . . . . . . . . . 535 Querying a Database by Using ADO .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535 The Northwind Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536 Creating the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536 Using ADO .NET to Query Order Information . . . . . . . . . . . . . . . . . . . . . . 538 Querying a Database by Using LINQ to SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549 Defining an Entity Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .549 Creating and Running a LINQ to SQL Query . . . . . . . . . . . . . . . . . . . . . . 551 Deferred and Immediate Fetching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553 Joining Tables and Creating Relationships . . . . . . . . . . . . . . . . . . . . . . . . . 554 Deferred and Immediate Fetching Revisited . . . . . . . . . . . . . . . . . . . . . . . 558 Defining a Custom DataContext Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559 Using LINQ to SQL to Query Order Information . . . . . . . . . . . . . . . . . . .560 Chapter 25 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .564 . 26 Displaying and Editing Data by Using the Entity Framework and Data Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565 Using Data Binding with the Entity Framework . . . . . . . . . . . . . . . . . . . . . . . . . 566 Using Data Binding to Modify Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583 Updating Existing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583 Handling Conflicting Updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .584 Adding and Deleting Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 Chapter 26 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596 Table of Contents xv Part VI .Building .Professional .Solutions .with . Visual .Studio .2010 . 27 Introducing the Task Parallel Library . . . . . . . . . . . . . . . . . . . . . . 599 Why Perform Multitasking by Using Parallel Processing? . . . . . . . . . . . . . . . . .600 The Rise of the Multicore Processor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601 Implementing Multitasking in a Desktop Application . . . . . . . . . . . . . . . . . . . . 602 Tasks, Threads, and the ThreadPool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603 Creating, Running, and Controlling Tasks . . . . . . . . . . . . . . . . . . . . . . . . .604 Using the Task Class to Implement Parallelism . . . . . . . . . . . . . . . . . . . . .608 Abstracting Tasks by Using the Parallel Class . . . . . . . . . . . . . . . . . . . . . . 617 Returning a Value from a Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624 Using Tasks and User Interface Threads Together . . . . . . . . . . . . . . . . . . . . . . . 628 Canceling Tasks and Handling Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632 The Mechanics of Cooperative Cancellation . . . . . . . . . . . . . . . . . . . . . . . 633 Handling Task Exceptions by Using the AggregateException Class . . . . 641 Using Continuations with Canceled and Faulted Tasks . . . . . . . . . . . . . .645 Chapter 27 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .646 . 28 Performing Parallel Data Access . . . . . . . . . . . . . . . . . . . . . . . . . . 649 Using PLINQ to Parallelize Declarative Data Access . . . . . . . . . . . . . . . . . . . . . . 650 Using PLINQ to Improve Performance While Iterating Through a Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650 Specifying Options for a PLINQ Query . . . . . . . . . . . . . . . . . . . . . . . . . . . 655 Canceling a PLINQ Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656 Synchronizing Concurrent Imperative Data Access . . . . . . . . . . . . . . . . . . . . . . 656 Locking Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659 Synchronization Primitives in the Task Parallel Library . . . . . . . . . . . . . . 661 Cancellation and the Synchronization Primitives . . . . . . . . . . . . . . . . . . .668 The Concurrent Collection Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .668 Using a Concurrent Collection and a Lock to Implement Thread-Safe Data Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670 Chapter 28 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681 xvi Table of Contents . 29 Creating and Using a Web Service . . . . . . . . . . . . . . . . . . . . . . . . 683 What Is a Web Service? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .684 The Role of Windows Communication Foundation . . . . . . . . . . . . . . . . .684 Web Service Architectures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .684 SOAP Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685 REST Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687 Building Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .688 Creating the ProductInformation SOAP Web Service . . . . . . . . . . . . . . .689 SOAP Web Services, Clients, and Proxies . . . . . . . . . . . . . . . . . . . . . . . . . . 697 Consuming the ProductInformation SOAP Web Service . . . . . . . . . . . . 698 Creating the ProductDetails REST Web Service . . . . . . . . . . . . . . . . . . . . 704 Consuming the ProductDetails REST Web Service . . . . . . . . . . . . . . . . . . 711 Chapter 29 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715 Appendix . Interoperating with Dynamic Languages . . . . . . . . . . . . . . . . . . 717 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727 Microsoft is interested in hearing your feedback so we can continually improve our books and learning resources for you. To participate in a brief online survey, please visit: www.microsoft.com/learning/booksurvey/ What do you think of this book? We want to hear from you! . xvii Acknowledgments An oft-repeated fable is that the workmen who paint the Forth Railway Bridge, a large Victorian cantilever structure that spans the Firth of Forth just north of Edinburgh, have a job for life . According to the myth, it takes them several years to paint it from one end to the other, and when they have finished they have to start over again . I am not sure whether this is due to the ferocity of the Scottish weather, or the sensitivity of the paint that is used, although my daughter insists it is simply that the members of Edinburgh City Council have yet to decide on a color scheme that they really like for the bridge . I sometimes feel that this book has similar attributes . No sooner have I completed an edition and seen it published, then Microsoft announces another cool update for Visual Studio and C#, and my friends at Microsoft Press contact me and say, “What are your plans for the next edition?” However, unlike painting the Forth Railway Bridge, working on a new edition of this text is always an enjoyable task with a lot more scope for inventiveness than trying to work out new ways to hold a paint brush . There is always something novel to learn and innovative technology to play with . In this edition, I cover the new features of C# 4 .0 and the .NET Framework 4 .0, which developers will find invaluable for building applications that can take advantage of the increasingly powerful hardware now becoming available . Hence, although this work appears to be a never-ending task, it is always fruitful and pleasurable . A large part of the enjoyment when working on a project such as this is the opportunity to collaborate with a highly motivated group of talented people within Microsoft Press, the developers at Microsoft working on Visual Studio 2010, and the people who review each chapter and make suggestions for various improvements . I would especially like to single out Rosemary Caperton and Stephen Sagman who have worked tirelessly to keep the project on track, to Per Blomqvist who reviewed (and corrected) each chapter, and to Roger LeBlanc who had the thankless task of copy-editing the manuscript and converting my prose into English . I must also make special mention of Michael Blome who provided me with early ­access to software and answered the many questions that I had concerning the Task Parallal Library . Several members of Content Master were kept gainfully employed reviewing and testing the code for the exercises—thanks Mike Sumsion, Chris Cully, James Millar, and Louisa Perry . Of course, I must additionally thank Jon Jagger who co-authored the first edition of this book with me back in 2001 . Last but by no means least, I must thank my family . My wife Diana is a wonderful source of inspiration . When writing Chapter 28 on the Task Parallel Library I had a mental block and had to ask her how she would explain Barrier methods . She looked at me quizzically, and gave a reply that although anatomically correct if I was in a doctor’s surgery, indicated that either I had not phrased the question very carefully or that she had completely mis- understood what I was asking! James has now grown up and will soon have to learn what real work entails if he is to keep Diana and myself in the manner to which we would like to ­become ­accustomed in our dotage . Francesca has also grown up, and seems to have refined a ­strategy for getting all she wants without doing anything other than looking at me with wide, bright eyes, and smiling . Finally, “Up the Gills!” —John Sharp . xix Introduction Microsoft Visual C# is a powerful but simple language aimed primarily at developers creating applications by using the Microsoft .NET Framework . It inherits many of the best features of C++ and Microsoft Visual Basic, but few of the inconsistencies and anachronisms, resulting in a cleaner and more logical language . C# 1 .0 made its public debut in 2001 . The advent of C# 2 .0 with Visual Studio 2005 saw several important new features added to the language, including Generics, Iterators, and anonymous methods . C# 3 .0 which was released with Visual Studio 2008, added extension methods, lambda expressions, and most famously of all, the Language Integrated Query facility, or LINQ . The latest incarnation of the language, C# 4 .0, provides further enhancements that improve its interoperability with other languages and technologies . These features include support for named and optional arguments, the ­dynamic type which indicates that the language runtime should implement late binding for an object, and variance which resolves some issues in the way in which generic interfaces are defined . C# 4 .0 takes advantage of the latest version of the .NET Framework, also version 4 .0 . There are many additions to the .NET Framework in this release, but arguably the most significant are the classes and types that constitute the Task Parallel Library (TPL) . Using the TPL, you can now build highly scalable applications that can take full advantage of multi-core processors quickly and easily . The support for Web services and Windows Communication Foundation (WCF) has also been extended; you can now build services that follow the REST model as well as the more traditional SOAP scheme . The development environment provided by Microsoft Visual Studio 2010 makes all these powerful features easy to use, and the many new wizards and enhancements included in Visual Studio 2010 can greatly improve your productivity as a developer . Who .This .Book .Is .For This book assumes that you are a developer who wants to learn the fundamentals of ­programming with C# by using Visual Studio 2010 and the .NET Framework version 4 .0 . In this book, you will learn the features of the C# language, and then use them to build applica- tions running on the Microsoft Windows operating system . By the time you complete this book, you will have a thorough understanding of C# and will have used it to build Windows Presentation Foundation applications, access Microsoft SQL Server databases by using ADO . NET and LINQ, build responsive and scalable applications by using the TPL, and create REST and SOAP Web services by using WCF . xx Introduction Finding .Your .Best .Starting .Point .in .This .Book This book is designed to help you build skills in a number of essential areas . You can use this book if you are new to programming or if you are switching from another programming lan- guage such as C, C++, Java, or Visual Basic . Use the following table to find your best starting point . If you are Follow these steps New to object-oriented programming . 1 . . .Install the practice files as described in the next section, “Installing and Using the Practice Files .” . 2 . . . Work through the chapters in Parts I, II, and III sequentially . . 3 . . .Complete Parts IV, V, and VI as your level of ­experience and interest dictates . Familiar with ­procedural ­programming ­languages such as C, but new to C# . 1 . . .Install the practice files as described in the next section, “Installing and Using the Practice Files .” Skim the first five chapters to get an overview of C# and Visual Studio 2010, and then concentrate on Chapters 6 through 21 . . 2 . . .Complete Parts IV, and V, and VI as your level of experience and interest dictates . Migrating from an ­object-oriented ­language such as C++, or Java . 1 . . .Install the practice files as described in the next section, “Installing and Using the Practice Files .” . 2 . . .Skim the first seven chapters to get an overview of C# and Visual Studio 2010, and then concen- trate on Chapters 8 through 21 . . 3 . . .For information about building Windows ­applications and using a database, read Parts IV and V . . 4 . . .For information about building scalable ­applications and Web services, read Part VI . Introduction xxi If you are Follow these steps Switching from Visual Basic 6 . 1 . . .Install the practice files as described in the next section, “Installing and Using the Practice Files .” . 2 . . .Work through the chapters in Parts I, II, and III sequentially . . 3 . . .For information about building Windows ­applications, read Part IV . . 4 . . .For information about accessing a database, read Part V . . 5 . . .For information about building scalable ­applications and Web services, read Part VI . . 6 . . .Read the Quick Reference sections at the end of the chapters for information about specific C# and Visual Studio 2010 constructs . Referencing the book after working through the exercises . 1 . . .Use the index or the Table of Contents to find information about particular subjects . . 2 . . .Read the Quick Reference sections at the end of each chapter to find a brief review of the syntax and techniques presented in the chapter . Conventions .and .Features .in .This .Book This book presents information using conventions designed to make the information read- able and easy to follow . Before you start, read the following list, which explains conventions you’ll see throughout the book and points out helpful features that you might want to use . Conventions n Each exercise is a series of tasks . Each task is presented as a series of numbered steps (1, 2, and so on) . A round bullet (•) indicates an exercise that has only one step . n Notes labeled “tip” provide additional information or alternative methods for ­completing a step successfully . n Notes labeled “important” alert you to information you need to check before continuing . n Text that you type appears in bold . xxii Introduction n A plus sign (+) between two key names means that you must press those keys at the same time . For example, “Press Alt+Tab” means that you hold down the Alt key while you press the Tab key . Other Features n Sidebars throughout the book provide more in-depth information about the ­exercise . The sidebars might contain background information, design tips, or ­features related to the information being discussed . n Each chapter ends with a Quick Reference section . The Quick Reference section ­contains quick reminders of how to perform the tasks you learned in the chapter . Prerelease .Software This book was written and tested against Visual Studio 2010 Beta 2 . We did review and test our examples against the final release of the software . However, you might find minor differ- ences between the production release and the examples, text, and screenshots in this book . Hardware .and .Software .Requirements You’ll need the following hardware and software to complete the practice exercises in this book: n Microsoft Windows 7 Home Premium, Windows 7 Professional, Windows 7 Enterprise, or Windows 7 Ultimate . The exercises will also run using Microsoft Windows Vista with Service Pack 2 or later . n Microsoft Visual Studio 2010 Standard, Visual Studio 2010 Professional, or Microsoft Visual C# 2010 Express and Microsoft Visual Web Developer 2010 Express . n Microsoft SQL Server 2008 Express (this is provided with all editions of Visual Studio 2010, Visual C# 2010 Express, and Visual Web Developer 2010 Express) . n 1 .6 GHz processor, or faster . Chapters 27 and 28 require a dual-core or better processor . n 1 GB for x32 processor, 2 GB for an x64 processor, of available, physical RAM . n Video (1024 ×768 or higher resolution) monitor with at least 256 colors . n CD-ROM or DVD-ROM drive . n Microsoft mouse or compatible pointing device You will also need to have Administrator access to your computer to configure SQL Server 2008 Express Edition . Introduction xxiii Code .Samples The companion CD inside this book contains the code samples that you’ll use as you perform the exercises . By using the code samples, you won’t waste time creating files that aren’t rel- evant to the exercise . The files and the step-by-step instructions in the lessons also let you learn by doing, which is an easy and effective way to acquire and remember new skills . Installing the Code Samples Follow these steps to install the code samples and required software on your computer so that you can use them with the exercises . . 1 . . Remove the companion CD from the package inside this book and insert it into your CD-ROM drive . Note  An end user license agreement should open automatically . If this agreement does not ­appear, open My Computer on the desktop or Start menu, double-click the icon for your CD-ROM drive, and then double-click StartCD .exe . . 2 . . Review the end user license agreement . If you accept the terms, select the accept ­option and then click Next . A menu will appear with options related to the book . . 3 . . Click Install .Code .Samples . . 4 . . Follow the instructions that appear . The code samples are installed to the following location on your computer: Documents\Microsoft Press\Visual CSharp Step By Step Using the Code Samples Each chapter in this book explains when and how to use any code samples for that chapter . When it’s time to use a code sample, the book will list the instructions for how to open the files . For those of you who like to know all the details, here’s a list of the code sample Visual Studio 2010 projects and solutions, grouped by the folders where you can find them . In many cases, the exercises provide starter files and completed versions of the same projects which you can use as a reference . The completed projects are stored in folders with the suffix “- Complete” . xxiv Introduction Project Description Chapter .1 TextHello This project gets you started . It steps through the creation of a simple program that displays a text-based greeting . WPFHello This project displays the greeting in a window by using Windows Presentation Foundation . Chapter .2 PrimitiveDataTypes This project demonstrates how to declare variables by using each of the primitive types, how to assign values to these variables, and how to display their values in a window . MathsOperators This program introduces the arithmetic operators (+ – * / %) . Chapter .3 Methods In this project, you’ll re-examine the code in the previous project and investigate how it uses methods to structure the code . DailyRate This project walks you through writing your own methods, running the methods, and stepping through the method calls by using the Visual Studio 2010 debugger . DailyRate Using Optional Parameters This project shows you how to define a method that takes optional parameters, and call the method by using named arguments . Chapter .4 Selection This project shows how to use a cascading if statement to implement complex logic, such as comparing the ­equivalence of two dates . SwitchStatement This simple program uses a switch statement to convert characters into their XML representations . Chapter .5 WhileStatement This project demonstrates a while statement that reads the contents of a source file one line at a time and displays each line in a text box on a form . DoStatement This project uses a do statement to convert a decimal num- ber to its octal representation . Introduction xxv Project Description Chapter .6 MathsOperators This project revisits the MathsOperators project from Chapter 2, “Working with Variables, Operators, and Expressions,” and shows how various unhandled exceptions can make the program fail . The try and catch keywords then make the application more robust so that it no longer fails . Chapter .7 Classes This project covers the basics of defining your own classes, complete with public constructors, methods, and private fields . It also shows how to create class instances by using the new keyword and how to define static methods and fields . Chapter .8 Parameters This program investigates the difference between value ­parameters and reference parameters . It demonstrates how to use the ref and out keywords . Chapter .9 StructsAndEnums This project defines a struct type to represent a calendar date . Chapter .10 Cards Using Arrays This project shows how to use arrays to model hands of cards in a card game . Cards Using Collections This project shows how to restructure the card game ­program to use collections rather than arrays . Chapter .11 ParamsArrays This project demonstrates how to use the params keyword to create a single method that can accept any number of int arguments . Chapter .12 Vehicles This project creates a simple hierarchy of vehicle classes by using inheritance . It also demonstrates how to define a ­virtual method . ExtensionMethod This project shows how to create an extension method for the int type, providing a method that converts an integer value from base 10 to a different number base . xxvi Introduction Project Description Chapter .13 Drawing Using Interfaces This project implements part of a graphical drawing pack- age . The project uses interfaces to define the methods that drawing shapes expose and implement . Drawing This project extends the Drawing Using Interfaces project to factor common functionality for shape objects into abstract classes . Chapter .14 UsingStatement This project revisits a small piece of code from Chapter 5, “Using Compound Assignment and Iteration Statements” and reveals that it is not exception-safe . It shows you how to make the code exception-safe with a using statement . Chapter .15 WindowProperties This project presents a simple Windows application that uses several properties to display the size of its main window . The display updates automatically as the user resizes the window . AutomaticProperties This project shows how to create automatic properties for a class, and use them to initialize instances of the class . Chapter .16 Indexers This project uses two indexers: one to look up a person’s phone number when given a name, and the other to look up a person’s name when given a phone number . Chapter .17 Clock Using Delegates This project displays a World clock showing the local time as well as the times in London, New York, and Tokyo . The appli- cation uses delegates to start and stop the clock displays . Clock Using Events This version of the World clock application uses events to start and stop the clock display . Chapter .18 BinaryTree This solution shows you how to use Generics to build a type- safe structure that can contain elements of any type . BuildTree This project demonstrates how to use Generics to implement a typesafe method that can take parameters of any type . BinaryTreeTest This project is a test harness that creates instances of the Tree type defined in the BinaryTree project . Introduction xxvii Project Description Chapter .19 BinaryTree This project shows you how to implement the generic IEnumerator interface to create an enumerator for the generic Tree class . IteratorBinaryTree This solution uses an Iterator to generate an enumerator for the generic Tree class . EnumeratorTest This project is a test harness that tests the enumerator and iterator for the Tree class . Chapter .20 QueryBinaryTree This project shows how to use LINQ queries to retrieve data from a binary tree object . Chapter .21 ComplexNumbers This project defines a new type that models complex num- bers, and implements common operators for this type . Chapter .22 BellRingers This project is a Windows Presentation Foundation applica- tion demonstrating how to define styles and use basic WPF controls . Chapter .23 BellRingers This project is an extension of the application created in Chapter 22, “Introducing Windows Presentation Foundation,” but with drop-down and pop-up menus added to the user interface . Chapter .24 OrderTickets This project demonstrates how to implement business rules for validating user input in a WPF application, using custom- er order information as an example . Chapter .25 ReportOrders This project shows how to access a database by using ADO . NET code . The application retrieves information from the Orders table in the Northwind database . LINQOrders This project shows how to use LINQ to SQL to access a data- base and retrieve information from the Orders table in the Northwind database . xxviii Introduction Project Description Chapter .26 Suppliers This project demonstrates how to use data binding with a WPF application to display and format data retrieved from a database in controls on a WPF form . The application also enables the user to modify information in the Products table in the Northwind database . Chapter .27 GraphDemo This project generates and displays a complex graph on a WPF form . It uses a single thread to perform the calculations . GraphDemo Using Tasks This version of the GraphDemo project creates multiple tasks to perform the calculations for the graph in parallel . GraphDemo Using Tasks that Return Results This is an extended version of the GraphDemo Using Tasks project that shows how to return data from a task . GraphDemo Using the Parallel Class This version of the GraphDemo project uses the Parallel class to abstract out the process of creating and managing tasks . GraphDemo Canceling Tasks This project shows how to implement cancelation to halt tasks in a controlled manner before they have completed ParallelLoop This application provides an example showing when you should not use the Parallel class to create and run tasks . Chapter .28 CalculatePI This project uses a statistical sampling algorithm to calculate an approximation for PI . It uses parallel tasks . PLINQ This project shows some examples of using PLINQ to query data by using parallel tasks . Introduction xxix Project Description Chapter .29 ProductInformationService This project implements a SOAP Web service built by using WCF . The Web service exposes a method that returns pricing information for products from the Northwind database . ProductDetailsService This projects implements a REST Web service built by using WCF . The Web service provides a method that returns the details of a specified product from the Northwind database . ProductDetailsContracts This project contains the service and data contracts imple- mented by the ProductDetailsService Web service . ProductClient This project shows how to create a WPF application that consumes a Web service . It shows how to invoke the Web methods in the ProductInformationService and ProductDetailsService Web services . Uninstalling the Code Samples Follow these steps to remove the code samples from your computer . . 1 . . In Control .Panel, under Programs, click Uninstall .a .program . . 2 . . From the list of currently installed programs, select Microsoft Visual C# 2010 Step By Step . . 3 . . Click Uninstall . . 4 . . Follow the instructions that appear to remove the code samples . xxx Introduction Find .Additional .Content .Online As new or updated material becomes available that complements your book, it will be posted online on the Microsoft Press Online Developer Tools Web site . The type of material you might find includes updates to book content, articles, links to companion content, ­errata, sample chapters, and more . This Web site is available at www .microsoft .com/learning/ books/online/developer, and is updated periodically . Digital Content for Digital Book Readers: If you bought a digital-only edition of this book, you can enjoy select content from the print edition’s companion CD. Visit http://go.microsoft.com/fwlink/?LinkId=184386 to get your downloadable content. This content is always up-to-date and available to all readers. Support .for .This .Book Every effort has been made to ensure the accuracy of this book and the contents of the companion CD . As corrections or changes are collected, they will be added to a Microsoft Knowledge Base article . Microsoft Press provides support for books and companion CDs at the following Web site: http://www.microsoft.com/learning/support/books/ . Questions and Comments If you have comments, questions, or ideas regarding the book or the companion CD, or questions that are not answered by visiting the sites above, please send them to Microsoft Press via e-mail to mspinput@microsoft.com. Please note that Microsoft software product support is not offered through the above address . Microsoft Visual C# 2010 Step by Step . 1 Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 In this part: Welcome to C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Working with Variables, Operators, and Expressions . . . . . . . . . . . . . . . . . . . . . . . 27 Writing Methods and Applying Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Using Decision Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Using Compound Assignment and Iteration Statements . . . . . . . . . . . . . . . . . . . . 91 Managing Errors and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 . 3 Chapter 1 Welcome to C# After completing this chapter, you will be able to: n Use the Microsoft Visual Studio 2010 programming environment . n Create a C# console application . n Explain the purpose of namespaces . n Create a simple graphical C# application . Microsoft Visual C# is Microsoft’s powerful component-oriented language . C# plays an ­important role in the architecture of the Microsoft .NET Framework, and some people have compared it to the role that C played in the development of UNIX . If you already know a language such as C, C++, or Java, you’ll find the syntax of C# reassuringly familiar . If you are used to programming in other languages, you should soon be able to pick up the syntax and feel of C#; you just need to learn to put the braces and semicolons in the right place . I hope this is just the book to help you! In Part I, you’ll learn the fundamentals of C# . You’ll discover how to declare variables and how to use arithmetic operators such as the plus sign (+) and minus sign (–) to manipulate the values in variables . You’ll see how to write methods and pass arguments to methods . You’ll also learn how to use selection statements such as if and iteration statements such as while . Finally, you’ll understand how C# uses exceptions to handle errors in a graceful, easy-to-use manner . These topics form the core of C#, and from this solid foundation, you’ll progress to more advanced features in Part II through Part VI . Beginning .Programming .with .the .Visual .Studio .2010 . Environment Visual Studio 2010 is a tool-rich programming environment containing the functionality that you need to create large or small C# projects . You can even construct projects that seam- lessly combine modules written by using different programming languages such as C++, Visual Basic, and F# . In the first exercise, you will open the Visual Studio 2010 programming environment and learn how to create a console application . Note  A console application is an application that runs in a command prompt window rather than providing a graphical user interface . 4 Part I  Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 Create a console application in Visual Studio 2010 n If you are using Visual Studio 2010 Standard or Visual Studio 2010 Professional, ­perform the following operations to start Visual Studio 2010: . 1 . . On the Microsoft Windows task bar, click the Start button, point to All Programs, and then point to the Microsoft Visual Studio 2010 program group . . 2 . . In the Microsoft Visual Studio 2010 program group, click Microsoft Visual ­Studio 2010 . Visual Studio 2010 starts, like this: Note  If this is the first time you have run Visual Studio 2010, you might see a dialog box prompting you to choose your default development environment settings . Visual Studio 2010 can tailor itself according to your preferred development language . The various dialog boxes and tools in the integrated development environment (IDE) will have their default selections set for the language you choose . Select Visual C# Development Settings from the list, and then click the Start Visual Studio button . After a short delay, the Visual Studio 2010 IDE appears . n If you are using Visual C# 2010 Express, on the Microsoft Windows task bar, click the Start button, point to All Programs, and then click Microsoft Visual C# 2010 Express . Visual C# 2010 Express starts, like this: Chapter 1  Welcome to C# 5 Note  If this is the first time you have run Visual C# 2010 Express, you might see a dialog box prompting you to choose your default development environment settings . Select Expert Settings from the list, and then click the Start Visual Studio button . After a short ­delay, the Visual C# 2010 IDE appears . Note  To avoid repetition, throughout this book I simply state, “Start Visual Studio” when you need to open Visual Studio 2010 Standard, Visual Studio 2010 Professional, or Visual C# 2010 Express . Additionally, unless explicitly stated, all references to Visual Studio 2010 apply to Visual Studio 2010 Standard, Visual Studio 2010 Professional, and Visual C# ­2010 Express . n If you are using Visual Studio 2010 Standard or Visual Studio 2010 Professional, perform the following tasks to create a new console application: . 1 . . On the File menu, point to New, and then click Project . . The New Project dialog box opens . This dialog box lists the templates that you can use as a starting point for building an application . The dialog box categorizes templates according to the programming language you are using and the type of application . . 2 . . In the left pane, under Installed Templates, click Visual C#. In the middle pane, verify that the combo box at the top of the pane displays the text .NET Framework 4.0, and then click the Console Application icon . You might need to scroll the middle pane to see the Console Application icon . 6 Part I  Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 . 3 . . In the Location field, if you are using Windows Vista type C:\Users\YourName\ Documents\Microsoft .Press\Visual .CSharp .Step .By .Step\Chapter .1 . If you are using Windows 7, type C:\Users\YourName\My .Documents\Microsoft .Press\ Visual .CSharp .Step .By .Step\Chapter .1 . Replace the text YourName in these paths with your Windows user name . Note  To save space throughout the rest of this book, I will simply refer to the path­ “C:\Users\YourName\Documents” or “C:\Users\YourName\My Documents” as your Documents folder . Tip  If the folder you specify does not exist, Visual Studio 2010 creates it for you . . 4 . . In the Name field, type TextHello . . 5 . . Ensure that the Create directory for solution check box is selected, and then click OK . n If you are using Visual C# 2010 Express, perform the following tasks to create a new console application: . 1 . . On the File menu, click New Project . . 2 . . In the New Project dialog box, in the middle pane click the Console Application icon . . 3 . . In the Name field, type TextHello . Chapter 1  Welcome to C# 7 . 4 . . Click OK . . Visual C# 2010 Express saves solutions to the C:\Users\YourName\AppData\Local\ Temporary Projects folder by default . You can specify an alternative location when you save the solution . . 5 . . On the File menu, click Save TextHello As. . 6 . . In the Save Project dialog box, in the Location field specify the Microsoft .Press\ Visual .CSharp .Step .By .Step\Chapter .1 folder under your Documents folder . . 7. . Click Save . Visual Studio creates the project using the Console Application template and displays the starter code for the project, like this: The menu bar at the top of the screen provides access to the features you’ll use in the pro- gramming environment . You can use the keyboard or the mouse to access the menus and commands exactly as you can in all Windows-based programs . The toolbar is located beneath the menu bar and provides button shortcuts to run the most frequently used commands . The Code and Text Editor pane occupying the main part of the IDE displays the contents of source files . In a multifile project, when you edit more than one file, each source file has its own tab labeled with the name of the source file . You can click the tab to bring the named source file to the foreground in the Code and Text Editor window . The Solution Explorer pane (on the right side of the dialog box) displays the names of the files associated with the proj- ect, among other items . You can also double-click a file name in the Solution Explorer pane to bring that source file to the foreground in the Code and Text Editor window . 8 Part I  Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 Before writing the code, examine the files listed in Solution Explorer, which Visual Studio 2010 has created as part of your project: n Solution ‘TextHello’  This is the top-level solution file, of which there is one per appli- cation . If you use Windows Explorer to look at your Documents\Microsoft Press\Visual CSharp Step By Step\Chapter 1\TextHello folder, you’ll see that the actual name of this file is TextHello .sln . Each solution file contains references to one or more project files . n TextHello  This is the C# project file . Each project file references one or more files ­containing the source code and other items for the project . All the source code in a sin- gle project must be written in the same programming language . In Windows Explorer, this file is actually called TextHello .csproj, and it is stored in the \Microsoft Press\Visual CSharp Step By Step\Chapter 1\TextHello\TextHello folder under your Documents folder . n Properties  This is a folder in the TextHello project . If you expand it, you will see that it contains a file called AssemblyInfo .cs . AssemblyInfo .cs is a special file that you can use to add attributes to a program, such as the name of the author, the date the pro- gram was written, and so on . You can specify additional attributes to modify the way in which the program runs . Learning how to use these attributes is outside the scope of this book . n References  This is a folder that contains references to compiled code that your ap- plication can use . When code is compiled, it is converted into an assembly and given a unique name . Developers use assemblies to package useful bits of code they have writ- ten so that they can distribute it to other developers who might want to use the code in their applications . Many of the features that you will be using when writing applications using this book make use of assemblies provided by Microsoft with Visual Studio 2010 . n App .config  This is the application configuration file . You can specify settings that your application can use at runtime to modify its behavior, such as the version of the .NET Framework to use to run the application . You will learn more about this file in later chapters in this book . n Program .cs  This is a C# source file and is the one currently displayed in the Code and Text Editor window when the project is first created . You will write your code for the console application in this file . It also contains some code that Visual Studio 2010 ­provides automatically, which you will examine shortly . Writing .Your .First .Program The Program .cs file defines a class called Program that contains a method called Main . All methods must be defined inside a class . You will learn more about classes in Chapter 7, “Creating and Managing Classes and Objects .” The Main method is special—it designates the program’s entry point . It must be a static method . (You will look at methods in detail in Chapter 3, “Writing Methods and Applying Scope,” and Chapter 7 describes static methods .) Chapter 1  Welcome to C# 9 Important  C# is a case-sensitive language . You must spell Main with a capital M . In the following exercises, you write the code to display the message “Hello World” in the console; you build and run your Hello World console application; and you learn how namespaces are used to partition code elements . Write the code by using Microsoft IntelliSense . 1 . . In the Code and Text Editor window displaying the Program .cs file, place the cursor in the Main method immediately after the opening brace, {, and then press Enter to cre- ate a new line . On the new line, type the word Console, which is the name of a built- in class . As you type the letter C at the start of the word Console, an IntelliSense list appears . This list contains all of the C# keywords and data types that are valid in this context . You can either continue typing or scroll through the list and double-click the Console item with the mouse . Alternatively, after you have typed Con, the IntelliSense list automatically homes in on the Console item and you can press the Tab or Enter key to select it . Main should look like this: static void Main(string[] args) { Console } Note  Console is a built-in class that contains the methods for displaying messages on the screen and getting input from the keyboard . . 2 . . Type a period immediately after Console . Another IntelliSense list appears, displaying the methods, properties, and fields of the Console class . . 3 . . Scroll down through the list, select WriteLine, and then press Enter . Alternatively, you can continue typing the characters W, r, i, t, e, L until WriteLine is selected, and then press Enter . The IntelliSense list closes, and the word WriteLine is added to the source file . Main should now look like this: static void Main(string[] args) { Console.WriteLine } . 4 . . Type an opening parenthesis, ( . Another IntelliSense tip appears . This tip displays the parameters that the WriteLine method can take . In fact, WriteLine is an overloaded method, meaning that the Console class contains more than one method 10 Part I  Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 named WriteLine—it actually provides 19 different versions of this method . Each ver- sion of the WriteLine method can be used to output different types of data . (Chapter 3 describes overloaded methods in more detail .) Main should now look like this: static void Main(string[] args) { Console.WriteLine( } Tip  You can click the up and down arrows in the tip to scroll through the different ­overloads of WriteLine . . 5 . . Type a closing parenthesis, ) followed by a semicolon, ; . Main should now look like this: static void Main(string[] args) { Console.WriteLine(); } . 6 . . Move the cursor, and type the string “Hello .World”, including the quotation marks, between the left and right parentheses following the WriteLine method . Main should now look like this: static void Main(string[] args) { Console.WriteLine("Hello World"); } Tip  Get into the habit of typing matched character pairs, such as ( and ) and { and }, ­before filling in their contents . It’s easy to forget the closing character if you wait until after you’ve entered the contents . IntelliSense .Icons When you type a period after the name of a class, IntelliSense displays the name of ­every member of that class . To the left of each member name is an icon that depicts the type of member . Common icons and their types include the following: Icon Meaning method (discussed in Chapter 3) property (discussed in Chapter 15, “Implementing Properties to Access Fields”) Chapter 1  Welcome to C# 11 Icon Meaning class (discussed in Chapter 7) struct (discussed in Chapter 9, “Creating Value Types with Enumerations and Structures”) enum (discussed in Chapter 9) interface (discussed in Chapter 13, “Creating Interfaces and Defining Abstract Classes”) delegate (discussed in Chapter 17, “Interrupting Program Flow and Handling Events”) extension method (discussed in Chapter 12, “Working with Inheritance”) You will also see other IntelliSense icons appear as you type code in different contexts . Note  You will frequently see lines of code containing two forward slashes followed by ordinary text . These are comments . They are ignored by the compiler but are very useful for developers because they help document what a program is actually doing . For example: Console.ReadLine(); // Wait for the user to press the Enter key The compiler skips all text from the two slashes to the end of the line . You can also add multiline comments that start with a forward slash followed by an asterisk (/*) . The compiler skips every- thing until it finds an asterisk followed by a forward slash sequence (*/), which could be many lines lower down . You are actively encouraged to document your code with as many meaningful comments as necessary . Build and run the console application . 1 . . On the Build menu, click Build Solution . This action compiles the C# code, resulting in a program that you can run . The Output window appears below the Code and Text Editor window . Tip  If the Output window does not appear, on the View menu, click Output to display it . 12 Part I  Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 In the Output window, you should see messages similar to the following indicating how the program is being compiled: ------ Build started: Project: TextHello, Configuration: Debug x86 ---- CopyFilesToOutputDirectory: TextHello -> C:\Users\John\My Documents\Microsoft Press\Visual CSharp Step By Step\ Chapter 1\TextHello\TextHello\bin\Debug\TextHello.exe ========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ======== If you have made some mistakes, they will appear in the Error List window . The fol- lowing image shows what happens if you forget to type the closing quotation marks after the text Hello World in the WriteLine statement . Notice that a single mistake can ­sometimes cause multiple compiler errors . Tip  You can double-click an item in the Error List window, and the cursor will be placed on the line that caused the error . You should also notice that Visual Studio displays a wavy red line under any lines of code that will not compile when you enter them . If you have followed the previous instructions carefully, there should be no errors or warnings, and the program should build successfully . Tip  There is no need to save the file explicitly before building because the Build Solution command automatically saves the file . An asterisk after the file name in the tab above the Code and Text Editor window indicates that the file has been changed since it was last saved . Chapter 1  Welcome to C# 13 . 2 . . On the Debug menu, click Start Without Debugging . A command window opens, and the program runs . The message “Hello World” ­appears, and then the program waits for you to press any key, as shown in the ­following graphic: Note  The prompt “Press any key to continue . . .” is generated by Visual Studio; you did not write any code to do this . If you run the program by using the Start Debugging com- mand on the Debug menu, the application runs, but the command window closes immedi- ately without waiting for you to press a key . . 3 . . Ensure that the command window displaying the program’s output has the focus, and then press Enter . The command window closes, and you return to the Visual Studio 2010 programming environment . . 4 . . In Solution Explorer, click the TextHello project (not the solution), and then click the Show All Files toolbar button on the Solution Explorer toolbar—this is the leftmost ­button on the toolbar in the Solution Explorer window . Show All Files Entries named bin and obj appear above the Program .cs file . These entries correspond directly to folders named bin and obj in the project folder (Microsoft Press\Visual CSharp Step By Step\Chapter 1\TextHello\TextHello) . Visual Studio creates these fold- ers when you build your application, and they contain the executable version of the ­program together with some other files used to build and debug the application . . 5 . . In Solution Explorer, expand the bin entry . Another folder named Debug appears . 14 Part I  Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 Note  You might also see a folder called Release . . 6 . . In Solution Explorer, expand the Debug folder . Four more items appear, named TextHello .exe, TextHello .pdb, TextHello .vshost .exe, and TextHello .vshost .exe .manifest . The file TextHello .exe is the compiled program, and it is this file that runs when you click Start Without Debugging on the Debug menu . The other files contain information that is used by Visual Studio 2010 if you run your program in Debug mode (when you click Start Debugging on the Debug menu) . Using .Namespaces The example you have seen so far is a very small program . However, small programs can soon grow into much bigger programs . As a program grows, two issues arise . First, it is ­harder to understand and maintain big programs than it is to understand and maintain smaller programs . Second, more code usually means more names, more methods, and more classes . As the number of names increases, so does the likelihood of the project build failing because two or more names clash (especially when a program also uses third-party libraries written by developers who have also used a variety of names) . In the past, programmers tried to solve the name-clashing problem by prefixing names with some sort of qualifier (or set of qualifiers) . This solution is not a good one because it’s not scalable; names become longer, and you spend less time writing software and more time typing (there is a difference) and reading and rereading incomprehensibly long names . Namespaces help solve this problem by creating a named container for other identifiers, such as classes . Two classes with the same name will not be confused with each other if they live in different namespaces . You can create a class named Greeting inside the namespace named TextHello, like this: namespace TextHello { class Greeting { ... } } You can then refer to the Greeting class as TextHello.Greeting in your programs . If another developer also creates a Greeting class in a different namespace, such as NewNamespace, and installs it on your computer, your programs will still work as expected because they are using the TextHello.Greeting class . If you want to refer to the other developer’s Greeting class, you must specify it as NewNamespace.Greeting . Chapter 1  Welcome to C# 15 It is good practice to define all your classes in namespaces, and the Visual Studio 2010 ­environment follows this recommendation by using the name of your project as the top-level namespace . The .NET Framework class library also adheres to this recommendation; every class in the .NET Framework lives inside a namespace . For example, the Console class lives ­inside the System namespace . This means that its full name is actually System.Console . Of course, if you had to write the full name of a class every time you used it, the situation would be no better than prefixing qualifiers or even just naming the class with some ­globally unique name such SystemConsole and not bothering with a namespace . Fortunately, you can solve this problem with a using directive in your programs . If you return to the TextHello program in Visual Studio 2010 and look at the file Program .cs in the Code and Text Editor window, you will notice the following statements at the top of the file: using System; using System.Collections.Generic; using System.Linq; using System.Text; A using statement brings a namespace into scope . In subsequent code in the same file, you no longer have to explicitly qualify objects with the namespace to which they belong . The four namespaces shown contain classes that are used so often that Visual Studio 2010 au- tomatically adds these using statements every time you create a new project . You can add ­further using directives to the top of a source file . The following exercise demonstrates the concept of namespaces in more depth . Try longhand names . 1 . . In the Code and Text Editor window displaying the Program .cs file, comment out the first using directive at the top of the file, like this: //using System; . 2 . . On the Build menu, click Build Solution . The build fails, and the Error List window displays the following error message: The name ’Console’ does not exist in the current context. . 3 . . In the Error List window, double-click the error message . The identifier that caused the error is highlighted in the Program .cs source file . . 4 . . In the Code and Text Editor window, edit the Main method to use the fully qualified name System.Console . Main should look like this: static void Main(string[] args) { System.Console.WriteLine("Hello World"); } 16 Part I  Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 Note  When you type System, the names of all the items in the System namespace are displayed by IntelliSense . . 5 . . On the Build menu, click Build Solution . The build should succeed this time . If it doesn’t, make sure that Main is exactly as it ­appears in the preceding code, and then try building again . . 6 . . Run the application to make sure it still works by clicking Start Without Debugging on the Debug menu . Namespaces .and .Assemblies A using statement simply brings the items in a namespace into scope and frees you from having to fully qualify the names of classes in your code . Classes are compiled into assemblies . An assembly is a file that usually has the .dll file name extension, although strictly speaking, executable programs with the .exe file name extension are also assemblies . An assembly can contain many classes . The classes that the .NET Framework class li- brary comprises, such as System.Console, are provided in assemblies that are installed on your computer together with Visual Studio . You will find that the .NET Framework class library contains many thousands of classes . If they were all held in the same as- sembly, the assembly would be huge and difficult to maintain . (If Microsoft updated a single method in a single class, it would have to distribute the entire class library to all developers!) For this reason, the .NET Framework class library is split into a number of assemblies, partitioned by the functional area to which the classes they contain relate . For ex- ample, there is a “core” assembly that contains all the common classes, such as System. Console, and there are further assemblies that contain classes for manipulating da- tabases, ­accessing Web services, building graphical user interfaces, and so on . If you want to make use of a class in an assembly, you must add to your project a reference to that assembly . You can then add using statements to your code that bring the items in namespaces in that assembly into scope . You should note that there is not necessarily a 1:1 equivalence between an assembly and a namespace; a single assembly can contain classes for multiple namespaces, and a single namespace can span multiple assemblies . This all sounds very confusing at first, but you will soon get used to it . When you use Visual Studio to create an application, the template you select auto- matically includes references to the appropriate assemblies . For example, in Solution Chapter 1  Welcome to C# 17 Explorer for the TextHello project, expand the References folder . You will see that a Console application automatically includes references to assemblies called Microsoft. CSharp, System, System.Core, System.Data, System.Data.DataExtensions, System.Xml, and System.Xml.Linq . You can add references for additional assemblies to a project by right-clicking the References folder and clicking Add Reference—you will perform this task in later exercises . Creating .a .Graphical .Application So far, you have used Visual Studio 2010 to create and run a basic Console application . The Visual Studio 2010 programming environment also contains everything you need to create graphical Windows-based applications . You can design the forms-based user interface of a Windows application interactively . Visual Studio 2010 then generates the program state- ments to implement the user interface you’ve designed . Visual Studio 2010 provides you with two views of a graphical application: the design view and the code view . You use the Code and Text Editor window to modify and maintain the code and logic for a graphical application, and you use the Design View window to lay out your user interface . You can switch between the two views whenever you want . In the following set of exercises, you’ll learn how to create a graphical application by using Visual Studio 2010 . This program will display a simple form containing a text box where you can enter your name and a button that displays a personalized greeting in a message box when you click the button . Note  Visual Studio 2010 provides two templates for building graphical applications—the Windows Forms Application template and the WPF Application template . Windows Forms is a technology that first appeared with the .NET Framework version 1 .0 . WPF, or Windows Presentation Foundation, is an enhanced technology that first appeared with the .NET Framework version 3 .0 . It provides many additional features and capabilities over Windows Forms, and you should consider using it in preference to Windows Forms for all new development . Create a graphical application in Visual Studio 2010 n If you are using Visual Studio 2010 Standard or Visual Studio 2010 Professional, perform the following operations to create a new graphical application: . 1 . . On the File menu, point to New, and then click Project . The New Project dialog box opens . 18 Part I  Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 . 2 . . In the left pane, under Installed Templates, click Visual C# . . 3 . . In the middle pane, click the WPF Application icon . . 4 . . Ensure that the Location field refers to the \Microsoft Press\Visual CSharp Step By Step\Chapter 1 folder under your Documents folder . . 5 . . In the Name field, type WPFHello . . 6 . . In the Solution field, ensure that Create new solution is selected . This action creates a new solution for holding the project . The alternative, Add to Solution, adds the project to the TextHello solution . . 7 . . Click OK . n If you are using Visual C# 2010 Express, perform the following tasks to create a new graphical application: . 1 . . On the File menu, click New Project . . 2 . . If the New Project message box appears, click Save to save your changes to the TextHello project . In the Save Project dialog box, verify that the Location field is set to Microsoft Press\Visual CSharp Step By Step\Chapter 1 under your Documents folder, and then click Save . . 3 . . In the New Project dialog box, click the WPF Application icon . . 4 . . In the Name field, type WPFHello . . 5 . . Click OK . Visual Studio 2010 closes your current application and creates the new WPF application . It displays an empty WPF form in the Design View window, together with another win- dow containing an XAML description of the form, as shown in the following graphic: Chapter 1  Welcome to C# 19 Tip  Close the Output and Error List windows to provide more space for displaying the Design View window . XAML stands for Extensible Application Markup Language and is an XML-like language used by WPF applications to define the layout of a form and its contents . If you have knowledge of XML, XAML should look familiar . You can actually define a WPF form completely by writing an XAML description if you don’t like using the Design View window of Visual Studio or if you don’t have access to Visual Studio; Microsoft provides a XAML editor called XAMLPad that is installed with the Windows Software Development Kit (SDK) . In the following exercise, you use the Design View window to add three controls to the Windows form and examine some of the C# code automatically generated by Visual Studio 2010 to implement these controls . Create the user interface . 1 . . Click the Toolbox tab that appears to the left of the form in the Design View window . The Toolbox appears, partially obscuring the form, and displays the various compo- nents and controls that you can place on a Windows form . Expand the Common WPF Controls section . This section displays a list of controls that are used by most WPF ap- plications . The All Controls section displays a more extensive list of controls . . 2 . . In the Common WPF Controls section, click Label, and then drag the label control onto the visible part of the form . A label control is added to the form (you will move it to its correct location in a ­moment), and the Toolbox disappears from view . Tip  If you want the Toolbox to remain visible but not to hide any part of the form, click the Auto Hide button to the right in the Toolbox title bar . (It looks like a pin .) The Toolbox appears permanently on the left side of the Visual Studio 2010 window, and the Design View window shrinks to accommodate it . (You might lose a lot of space if you have a ­low-resolution screen .) Clicking the Auto Hide button once more causes the Toolbox to disappear again . . 3 . . The label control on the form is probably not exactly where you want it . You can click and drag the controls you have added to a form to reposition them . Using this tech- nique, move the label control so that it is positioned toward the upper left corner of the form . (The exact placement is not critical for this application .) 20 Part I  Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 Note  The XAML description of the form in the lower pane now includes the label control, together with properties such as its location on the form, governed by the Margin prop- erty . The Margin property consists of four numbers indicating the distance of each edge of the label from the edges of the form . If you move the control around the form, the value of the Margin property changes . If the form is resized, the controls anchored to the form’s edges that move are resized to preserve their margin values . You can prevent this by setting the Margin values to zero . You learn more about the Margin and also the Height and Width properties of WPF controls in Chapter 22, “Introducing Windows Presentation Foundation .” . 4 . . On the View menu, click Properties Window . If it was not already displayed, the Properties window appears on the lower right side of the screen, under Solution Explorer . You can specify the properties of controls by us- ing the XAML pane under the Design View window . However, the Properties window provides a more convenient way for you to modify the properties for items on a form, as well as other items in a project . It is context sensitive in that it displays the proper- ties for the currently selected item . If you click the title bar of the form displayed in the Design View window, you can see that the Properties window displays the properties for the form itself . If you click the label control, the window displays the properties for the label instead . If you click anywhere else on the form, the Properties window displays the properties for a mysterious item called a grid . A grid acts as a container for items on a WPF form, and you can use the grid, among other things, to indicate how items on the form should be aligned and grouped together . . 5 . . Click the label control on the form . In the Properties window, locate the FontSize ­property . Change the FontSize property to 20, and then in the Design View window click the title bar of the form . The size of the text in the label changes . . 6 . . In the XAML pane below the Design View window, examine the text that defines the label control . If you scroll to the end of the line, you should see the text FontSize=“20” . Any changes that you make by using the Properties window are automatically reflected in the XAML definitions and vice versa . Overtype the value of the FontSize property in the XAML pane, and change it back to 12 . The size of the text in the label in the Design View window changes back . . 7 . . In the XAML pane, examine the other properties of the label control . The properties that are listed in the XAML pane are only the ones that do not have default values . If you modify any property values by using the Properties Window, they appear as part of the label definition in the XAML pane . . 8 . . Change the value of the Content property from Label to Please .enter .your .name . Notice that the text displayed in the label on the form changes, although the label is too small to display it correctly . Chapter 1  Welcome to C# 21 . 9 . . In the Design View window, click the label control . Place the mouse over the right edge of the label control . It should change into a double-headed arrow to indicate that you can use the mouse to resize the control . Click the mouse and drag the right edge of the label control further to the right, until you can see the complete text for the label . . 10 . . Click the form in the Design View window, and then display the Toolbox again . . 11 . . In the Toolbox, click and drag the TextBox control onto the form . Move the text box control so that it is directly underneath the label control . Tip  When you drag a control on a form, alignment indicators appear automatically when the control becomes aligned vertically or horizontally with other controls . This gives you a quick visual cue for making sure that controls are lined up neatly . . 12 . . While the text box control is selected, in the Properties window, change the value of the Name property displayed at the top of the window to userName . Note  You will learn more about naming conventions for controls and variables in Chapter 2, “Working with Variables, Operators, and Expressions .” . 13 . . Display the Toolbox again, and then click and drag a Button control onto the form . Place the button control to the right of the text box control on the form so that the bottom of the button is aligned horizontally with the bottom of the text box . . 14 . . Using the Properties window, change the Name property of the button control to ok . And change the Content property from Button to OK . Verify that the caption of the button control on the form changes . . 15 . . Click the title bar of the MainWindow .xaml form in the Design View window . In the Properties window, change the Title property to Hello . . 16 . . In the Design View window, notice that a resize handle (a small square) appears on the lower right corner of the form when it is selected . Move the mouse pointer over the resize handle . When the pointer changes to a diagonal double-headed arrow, click and drag the pointer to resize the form . Stop dragging and release the mouse button when the spacing around the controls is roughly equal . Important  Click the title bar of the form and not the outline of the grid inside the form before resizing it . If you select the grid, you will modify the layout of the controls on the form but not the size of the form itself . The form should now look similar to the following figure . 22 Part I  Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 . 17 . . On the Build menu, click Build Solution, and verify that the project builds successfully . . 18 . . On the Debug menu, click Start Without Debugging . The application should run and display your form . You can type your name in the text box and click OK, but nothing happens yet . You need to add some code to process the Click event for the OK button, which is what you will do next . . 19 . . Click the Close button (the X in the upper-right corner of the form) to close the form and return to Visual Studio . You have managed to create a graphical application without writing a single line of C# code . It does not do much yet (you will have to write some code soon), but Visual Studio actually generates a lot of code for you that handles routine tasks that all graphical applications must perform, such as starting up and displaying a form . Before adding your own code to the ­application, it helps to have an understanding of what Visual Studio has generated for you . In Solution Explorer, expand the MainWindow .xaml node . The file MainWindow .xaml .cs ­appears . Double-click the file MainWindow .xaml .cs . The code for the form is displayed in the Code and Text Editor window . It looks like this: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; Chapter 1  Welcome to C# 23 using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WPFHello { /// /// Interaction logic for MainWindow.xaml /// public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } } In addition to a good number of using statements bringing into scope some namespaces that most WPF applications use, the file contains the definition of a class called MainWindow but not much else . There is a little bit of code for the MainWindow class known as a con- structor that calls a method called InitializeComponent, but that is all . (A constructor is a special method with the same name as the class . It is executed when an instance of the class is created and can contain code to initialize the instance . You will learn about constructors in Chapter 7 .) In fact, the application contains a lot more code, but most of it is generated automatically based on the XAML description of the form, and it is hidden from you . This hidden code performs operations such as creating and displaying the form, and creating and positioning the various controls on the form . The purpose of the code that you can see in this class is so that you can add your own ­methods to handle the logic for your application, such as determining what happens when the user clicks the OK button . Tip  You can also display the C# code file for a WPF form by right-clicking anywhere in the Design View window and then clicking View Code . At this point, you might be wondering where the Main method is and how the form gets ­displayed when the application runs; remember that Main defines the point at which the program starts . In Solution Explorer, you should notice another source file called App .xaml . If you double-click this file, the XAML description of this item appears . One property in the 24 Part I  Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 XAML code is called StartupUri, and it refers to the MainWindow .xaml file as shown in bold in the following code example: If you click the Design tab at the bottom of the XAML pane, the Design View window for App . xaml appears and displays the text “Intentionally left blank . The document root element is not supported by the visual designer” . This occurs because you cannot use the Design View window to modify the App .xaml file . Click the XAML tab to return to the XAML pane . If you expand the App .xaml node in Solution Explorer, you will see that there is also an Application .xaml .cs file . If you double-click this file, you will find it contains the following code: using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Windows; namespace WPFHello { /// /// Interaction logic for App.xaml /// public partial class App : Application { } } Once again, there are a number of using statements but not a lot else, not even a Main method . In fact, Main is there, but it is also hidden . The code for Main is generated based on the settings in the App .xaml file; in particular, Main will create and display the form specified by the StartupUri property . If you want to display a different form, you edit the App .xaml file . The time has come to write some code for yourself! Write the code for the OK button . 1 . . Click the MainWindow.xaml tab above the Code and Text Editor window to display MainWindow in the Design View window . Chapter 1  Welcome to C# 25 . 2 . . Double-click the OK button on the form . The MainWindow .xaml .cs file appears in the Code and Text Editor window, but a new method has been added called ok_Click . Visual Studio automatically generates code to call this method whenever the user clicks the OK button . This is an example of an event . You will learn much more about how events work as you progress through this book . . 3 . . Add the following code shown in bold to the ok_Click method: void ok_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Hello " + userName.Text); } This is the code that will run when the user clicks the OK button . Do not worry too much about the syntax of this code just yet (just make sure you copy it exactly as shown) because you will learn all about methods in Chapter 3 . The interesting part is the MessageBox.Show statement . This statement displays a message box containing the text “Hello” with whatever name the user typed into the username text box on the ­appended form . . 4 . . Click the MainWindow.xaml tab above the Code and Text Editor window to display MainWindow in the Design View window again . . 5 . . In the lower pane displaying the XAML description of the form, examine the Button ­element, but be careful not to change anything . Notice that it contains an element called Click that refers to the ok_Click method: