www.it-ebooks.info www.it-ebooks.info Programming C# 4.0 www.it-ebooks.info www.it-ebooks.info SIXTH EDITION Programming C# 4.0 Ian Griffiths, Matthew Adams, and Jesse Liberty Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo www.it-ebooks.info Programming C# 4.0, Sixth Edition by Ian Griffiths, Matthew Adams, and Jesse Liberty Copyright © 2010 Ian Griffiths and Matthew Adams. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles ( http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Editors: Mike Hendrickson and Laurel Ruma Production Editor: Adam Zaremba Copyeditor: Audrey Doyle Proofreader: Stacie Arellano Indexer: Jay Marchand Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: July 2001: First Edition. February 2002: Second Edition. May 2003: Third Edition. February 2005: Fourth Edition. December 2007: Fifth Edition. August 2010: Sixth Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Programming C# 4.0, the image of an African crowned crane, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein. ISBN: 978-0-596-15983-2 [M] 1280338225 www.it-ebooks.info Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv 1. Introducing C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Why C#? Why .NET? 1 The .NET Framework Class Library 2 Language Style 3 Composability 4 Managed Code 5 Continuity and the Windows Ecosystem 6 C# 4.0, .NET 4, and Visual Studio 2010 7 Summary 9 2. Basic Programming Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Getting Started 11 Namespaces and Types 14 Projects and Solutions 19 Comments, Regions, and Readability 24 Bad Comments 26 XML Documentation Comments 26 Variables 28 Variable Types 28 Expressions and Statements 35 Assignment Statements 38 Increment and Decrement Operators 38 Flow Control with Selection Statements 39 if Statements 40 switch and case Statements 45 Iteration Statements 47 foreach Statements 48 for Statements 50 while and do Statements 52 v www.it-ebooks.info Breaking Out of a Loop 53 Methods 55 Summary 58 3. Abstracting Ideas with Classes and Structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Divide and Conquer 59 Abstracting Ideas with Methods 59 Abstracting Ideas with Objects and Classes 62 Defining Classes 64 Representing State with Properties 64 Protection Levels 66 Initializing with a Constructor 68 Fields: A Place to Put Data 72 Fields Can Be Fickle, but const Is Forever 75 Read-only Fields and Properties 76 Related Constants with enum 79 Value Types and Reference Types 82 Too Many Constructors, Mr. Mozart 88 Overloading 88 Overloaded Methods and Default Named Parameters 89 Object Initializers 92 Defining Methods 95 Declaring Static Methods 98 Static Fields and Properties 99 Static Constructors 101 Summary 102 4. Extensibility and Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Association Through Composition and Aggregation 104 Inheritance and Polymorphism 106 Replacing Methods in Derived Classes 109 Hiding Base Members with new 109 Replacing Methods with virtual and override 112 Inheritance and Protection 114 Calling Base Class Methods 116 Thus Far and No Farther: sealed 118 Requiring Overrides with abstract 121 All Types Are Derived from Object 127 Boxing and Unboxing Value Types 127 C# Does Not Support Multiple Inheritance of Implementation 132 C# Supports Multiple Inheritance of Interface 132 Deriving Interfaces from Other Interfaces 135 Explicit Interface Implementation 136 vi | Table of Contents www.it-ebooks.info The Last Resort: Checking Types at Runtime 141 Summary 142 5. Composability and Extensibility with Delegates . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 Functional Composition with delegate 150 Generic Actions with Action<T> 156 Generic Predicates with Predicate<T> 160 Using Anonymous Methods 162 Creating Delegates with Lambda Expressions 163 Delegates in Properties 165 Generic Delegates for Functions 167 Notifying Clients with Events 171 Exposing Large Numbers of Events 180 Summary 183 6. Dealing with Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 When and How to Fail 191 Returning Error Values 194 Debugging with Return Values 200 Exceptions 201 Handling Exceptions 207 When Do finally Blocks Run? 214 Deciding What to Catch 215 Custom Exceptions 218 Summary 220 7. Arrays and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 Arrays 221 Construction and Initialization 222 Custom Types in Arrays 225 Array Members 230 Array Size 236 List<T> 243 Custom Indexers 247 Finding and Sorting 253 Collections and Polymorphism 254 Creating Your Own IEnumerable<T> 258 Summary 264 8. LINQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265 Query Expressions 265 Query Expressions Versus Method Calls 267 Extension Methods and LINQ 268 Table of Contents | vii www.it-ebooks.info let Clauses 271 LINQ Concepts and Techniques 271 Delegates and Lambdas 271 Functional Style and Composition 273 Deferred Execution 274 LINQ Operators 275 Filtering 275 Ordering 276 Concatenation 279 Grouping 280 Projections 282 Zipping 288 Getting Selective 289 Testing the Whole Collection 291 Aggregation 292 Set Operations 294 Joining 295 Conversions 296 Summary 297 9. Collection Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 Dictionaries 299 Common Dictionary Uses 301 IDictionary<TKey, TValue> 308 Dictionaries and LINQ 309 HashSet and SortedSet 310 Queues 311 Linked Lists 312 Stacks 313 Summary 314 10. Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 What Is a String? 316 The String and Char Types 317 Literal Strings and Chars 318 Escaping Special Characters 319 Formatting Data for Output 322 Standard Numeric Format Strings 323 Custom Numeric Format Strings 329 Dates and Times 332 Going the Other Way: Converting Strings to Other Types 336 Composite Formatting with String.Format 337 Culture Sensitivity 338 viii | Table of Contents www.it-ebooks.info [...]... 473 Choosing a Networking Technology Web Application with Client-Side Code NET Client and NET Server NET Client and External Party Web Service External Client and NET Web Service WCF Creating a WCF Project WCF Contracts WCF Test Client and Host Hosting a WCF Service x | Table of Contents www.it-ebooks.info 473 474 477 479 480 481 481 482 483 486 Writing a WCF Client Bidirectional Communication with... Data Access Technologies WCF Data Services Silverlight and Data Access Databases The Entity Data Model Generated Code Changing the Mapping Relationships Inheritance Queries LINQ to Entities Entity SQL Mixing ESQL and LINQ The EntityClient ADO.NET Provider Object Context Connection Handling Creating, Updating, and Deleting Transactions Optimistic Concurrency Context and Entity Lifetime WCF Data Services... Abstracting Ideas with Classes and Structs C# supports object-oriented programming, and this chapter describes the language features dedicated to these techniques Chapter 4, Extensibility and Polymorphism This chapter continues the discussion from the preceding chapter, illustrating how C# supports inheritance, interfaces, and related concepts Chapter 5, Composability and Extensibility with Delegates C# ... managed code Managed compilers do not produce raw executable code Instead, they produce an intermediate form of code called IL, the Intermediate Language.† The runtime decides exactly how to convert it into something executable One practical upshot of managed code is that a compiled C# program can run on both 32-bit and 64-bit systems without modification, and can even run on different processor architectures—it’s... Office interop with C# 4.0 static void Main(string[] args) { var wordApp = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word._Document doc = wordApp.Documents.Open("WordFile.docx", ReadOnly: true); dynamic docProperties = doc.BuiltInDocumentProperties; string authorName = docProperties["Author"].Value; doc.Close(SaveChanges: false); Console.WriteLine(authorName); } 8 | Chapter... and the OS Scheduler The Stack The Thread Pool Thread Affinity and Context Common Thread Misconceptions Multithreaded Coding Is Hard Multithreading Survival Strategies Synchronization Primitives Monitor Other Lock Types Other Coordination Mechanisms Events Countdown BlockingCollection Asynchronous Programming The Asynchronous Programming Model The Event-Based Asynchronous Pattern Ad Hoc Asynchrony The... Accessing Characters by Index Strings Are Immutable Getting a Range of Characters Composing Strings Splitting It Up Again Upper- and Lowercase Manipulating Text Mutable Strings with StringBuilder Finding and Replacing Content All Sorts of “Empty” Strings Trimming Whitespace Checking Character Types Encoding Characters Why Encodings Matter Encoding and Decoding Why Represent Strings As Byte Sequences?... automate certain kinds of tasks This chapter shows the API for doing this, and how you can extend the structural information through attributes Chapter 18, Dynamic One of the new features in C# 4.0 is support for dynamic binding This is particularly useful in certain interop scenarios, as we discuss in this chapter Chapter 19, Interop with COM and Win32 Sometimes it’s necessary for C# code to communicate... to errors Chapter 7, Arrays and Lists This chapter shows the tools C# offers for representing simple collections of information Chapter 8, LINQ It’s not enough merely to be able to represent collections, so this chapter shows how you can use the integrated query features in C# to process your collections of data Chapter 9, Collection Classes This chapter shows some of the more specialized classes for... from C# Chapter 15, Assemblies In this chapter, we show how to compile code into libraries for reuse, and how programs made up from multiple components work Chapter 16, Threads and Asynchronous Code Many programs need to deal with concurrency, and this chapter shows the tools and techniques available Chapter 17, Attributes and Reflection C# has the ability to inspect the structure of code, which makes . Service 48 0 WCF 48 1 Creating a WCF Project 48 1 WCF Contracts 48 2 WCF Test Client and Host 48 3 Hosting a WCF Service 48 6 x | Table of Contents www.it-ebooks.info Writing a WCF Client 49 3 Bidirectional. .NET Data Access Landscape 539 Classic ADO.NET 5 40 LINQ and Databases 544 Non-Microsoft Data Access Technologies 545 WCF Data Services 546 Silverlight and Data Access 546 Databases 547 The Entity. History: July 200 1: First Edition. February 200 2: Second Edition. May 200 3: Third Edition. February 200 5: Fourth Edition. December 200 7: Fifth Edition. August 201 0: Sixth Edition. Nutshell