c# 5.0 programmer’s reference...c# 5.0 programmer’s r eference published by john wiley &...

30

Upload: others

Post on 12-Apr-2020

17 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison
Page 2: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison
Page 3: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

C# 5.0 PROGRAMMER’S REFERENCE

INtROduCtION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiii

▶ PARt I thE C# ECOSyStEM

ChAPtER 1 The C# Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

ChAPtER 2 Writing a First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

ChAPtER 3 Program and Code File Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

▶ PARt II C# LANGuAGE ELEMENtS

ChAPtER 4 Data Types, Variables, and Constants . . . . . . . . . . . . . . . . . . . . . . . . 53

ChAPtER 5 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

ChAPtER 6 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

ChAPtER 7 Program Control Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151

ChAPtER 8 LINQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

ChAPtER 9 Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

ChAPtER 10 Tracing and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

▶ PARt III ObjECt-ORIENtEd PROGRAMMING

ChAPtER 11 OOP Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

ChAPtER 12 Classes and Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269

ChAPtER 13 Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303

ChAPtER 14 Collection Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317

ChAPtER 15 Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343

▶ PARt IV INtERACtING wIth thE ENVIRONMENt

ChAPtER 16 Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

ChAPtER 17 Configuration and Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393

ChAPtER 18 Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411

ChAPtER 19 File System Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425

ChAPtER 20 Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445

Continues

Page 4: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

▶ PARt V AdVANCEd tOPICS

ChAPtER 21 Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469

ChAPtER 22 Parallel Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485

ChAPtER 23 ADO .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509

ChAPtER 24 XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533

ChAPtER 25 Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563

ChAPtER 26 Reflection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581

ChAPtER 27 Cryptography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601

▶ PARt VI APPENdICES

APPENdIx A Solutions to Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625

APPENdIx b Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733

APPENdIx C Variable Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737

APPENdIx d Constant Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 741

APPENdIx E Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 743

APPENdIx F Method Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749

APPENdIx G Useful Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753

APPENdIx h Control Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757

APPENdIx I Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 761

APPENdIx j LINQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763

APPENdIx K Classes and Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773

APPENdIx L Collection Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777

APPENdIx M Generic Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783

APPENdIx N Printing and Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785

APPENdIx O Useful Exception Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 799

APPENdIx P Date and Time Format Specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 803

APPENdIx Q Other Format Specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807

APPENdIx R Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813

APPENdIx S Filesystem Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821

APPENdIx t Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835

APPENdIx u Parallel Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 843

Page 5: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

APPENdIx V XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849

APPENdIx w Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 859

APPENdIx x Reflection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 865

INdEx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 877

Page 6: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison
Page 7: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

Programmer’s reference

c# 5.0

Page 8: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison
Page 9: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

Rod Stephens

Programmer’s reference

c# 5.0

Page 10: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

c# 5.0 Programmer’s reference

Published by John Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com

Copyright © 2014 by John Wiley & Sons, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-1-118-84728-2ISBN: 978-1-118-84697-1 (ebk)ISBN: 978-1-118-84729-9 (ebk)

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2 1

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or pro-motional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the pub-lisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with stan-dard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://book-support.wiley.com. For more information about Wiley products, visit www.wiley.com.

Library of Congress Control Number: 2014930410

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.

Page 11: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

AbOut thE AuthOR

ROd StEPhENS started out as a mathematician, but while studying at MIT, he discovered how much fun programming is and has been programming profes-sionally ever since. During his career, he has worked on an eclectic assortment of applications in such fields as telephone switching, billing, repair dispatching, tax processing, wastewater treatment, concert ticket sales, cartography, and training for professional football players.

Rod has been a Microsoft Visual Basic Most Valuable Professional (MVP) for more than 10 years and has taught introductory programming at ITT Technical Institute. He has written more than two dozen books that have been translated into languages from all over the world, and more than 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.

Rod’s popular C# Helper website (www.CSharpHelper.com) receives almost a million post visits per year and contains thousands of pages of tips, tricks, and example programs for C# programmers, as well as example code for this book. His VB Helper website (www.vb-helper.com) contains similar material for Visual Basic programmers.

You can contact Rod at [email protected] or [email protected].

AbOut thE tEChNICAL EdItOR

bRIAN hOChGuRtEL has been doing .NET development for more than 10 years, and actually started his .NET experience with Rod Stephens when they wrote the Wiley book Visual Basic .NET and XML in 2002. Currently Brian works with C#, SQL Server, and SharePoint at Riverside Technology in Fort Collins, CO.

Page 12: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison
Page 13: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

ExECutIVE EdItOR Robert Elliott

PROjECt EdItOR Adaobi Obi Tulton

tEChNICAL EdItOR Brian Hochgurtel

PROduCtION EdItOR Daniel Scribner

COPy EdItOR San Dee Phillips

MANAGER OF CONtENt dEVELOPMENt ANd ASSEMbLy Mary Beth Wakefield

dIRECtOR OF COMMuNIty MARKEtING David Mayhew

MARKEtING MANAGER Ashley Zurcher

buSINESS MANAGER Amy Knies

VICE PRESIdENt ANd ExECutIVE GROuP PubLIShER Richard Swadley

ASSOCIAtE PubLIShER Jim Minatel

PROjECt COORdINAtOR, COVER Todd Klemme

COMPOSItOR Craig Woods, Happenstance Type-O-Rama

PROOFREAdER Nicole Hirschman

INdExER Johnna VanHoose Dinse

COVER dESIGNER Wiley

COVER IMAGE ©iStockphoto .com/W6

CREdItS

Page 14: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison
Page 15: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

ACKNOwLEdGMENtS

thANKS tO Bob Elliott, Adaobi Obi Tulton, John Mueller, San Dee Phillips, Daniel Scribner, and all the others who worked so hard to make this book possible.

Thanks also to technical editor Brian Hochgurtel for giving me the benefit of his valuable experience.

Page 16: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison
Page 17: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

CONtENtS

IntroductIon xxxiii

PARt I: thE C# ECOSyStEM

ChAPtER 1: thE C# ENVIRONMENt 3

Visual studio 3The c# compiler 4The cLr 6The .neT framework 8summary 9exercises 10

ChAPtER 2: wRItING A FIRSt PROGRAM 11

Types of Projects 11console applications 14Windows forms applications 16WPf applications 19Windows store applications 21summary 23exercises 24

ChAPtER 3: PROGRAM ANd COdE FILE StRuCtuRE 27

Hidden files 28Preprocessor Directives 31

#define and #undef 31#if, #else, #elif, and #endif 33#warning and #error 34#line 34#region and #endregion 35#pragma 36

code file structure 37The using Directive 38The namespace Statement 40Class Definitions 42

CONtENtS

IntroductIon xxxiii

Who should read This Book xxxivapproach xxxivWhich edition of Visual studio should You Use? xxxvHow This Book Is organized xxxviHow to Use This Book xxxviinecessary equipment xxxviiiconventions xxxviiisource code xxxixerrata xlp2p.wrox.com xlImportant UrLs xli

PARt I: thE C# ECOSyStEM

thE C# ENVIRONMENt 3

Visual studio 3The c# compiler 4The cLr 6The .neT framework 8summary 9exercises 10

wRItING A FIRSt PROGRAM 11

Types of Projects 11console applications 14Windows forms applications 16WPf applications 19Windows store applications 21summary 23exercises 24

Page 18: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

xvi

CONTENTS

comments 43End-of-line and Multiline Comments 43XML Comments 45

summary 48exercises 48

PARt II: C# LANGuAGE ELEMENtS

ChAPtER 4: dAtA tyPES, VARIAbLES, ANd CONStANtS 53

Data Types 54Value Versus Reference Types 57The var Keyword 58

Variable Declaration syntax 59Name 62Attributes 62Accessibility 63Static, Constant, and Volatile Variables 64

Initialization 65Classes and Structures 66Arrays 67Collections 68

Literal Type characters 69Data Type conversion 72

Implicit Conversion 73Casting 74Using the as Operator 76Casting Arrays 77Parsing 77Using System .Convert 78Using System .BitConverter 78ToString 79

scope 79Block Scope 79Method Scope 80Class Scope 81Restricting Scope 81

Parameter Declarations 82By Value 82By Reference 83For Output 84Unusual Circumstances and Exceptions 85

Page 19: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

xvii

CONTENTS

Properties 86enumerations 88nullable Types 92Delegates 93summary 95exercises 96

ChAPtER 5: OPERAtORS 99

arithmetic operators 100Result Data Type 100Shift Operators 101Increment and Decrement Operators 101

comparison operators 102Logical operators 103Bitwise operators 105conditional and null-coalescing operators 106assignment operators 107operator Precedence 108The stringBuilder class 110DateTime and Timespan operations 111operator overloading 112

Comparison Operators 113Logical Operators 115Type Conversion Operators 115

summary 117exercises 118

ChAPtER 6: MEthOdS 121

method Declarations 122Attributes 122Accessibility 124Modifiers 124Name 128Return Type 128Parameters 129Implementing Interfaces 133

extension methods 135Lambda expressions 136

Expression Lambdas 136Statement Lambdas 137Async Lambdas 138

Page 20: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

xviii

CONTENTS

Variance 139asynchronous methods 140

Calling EndInvoke Directly 140Handling a Callback 141Using Async and Await 144

summary 146exercises 147

ChAPtER 7: PROGRAM CONtROL StAtEMENtS 151

Decision statements 151if-else Statements 152switch Statements 153Enumerated Values 156Conditional and Null-coalescing Operators 157

Looping statements 157for Loops 157Noninteger for Loops 159while Loops 160do Loops 161foreach Loops 161Enumerators 163Iterators 164break Statements 165continue Statements 165

summary 166exercises 166

ChAPtER 8: LINQ 169

Introduction to LInQ 171Basic LInQ Query syntax 173

from 173where 174orderby 175select 175Using LINQ Results 177

advanced LInQ Query syntax 178join 178join into 179group by 179Aggregate Values 181

Page 21: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

xix

CONTENTS

Set Methods 182Limiting Results 183

other LInQ methods 184LInQ extension methods 185

Method-Based Queries 185Method-Based Queries with Lambda Functions 187Extending LINQ 188

LInQ to objects 189LInQ to XmL 189

XML Literals 190LINQ into XML 191LINQ out of XML 192

LInQ to aDo.neT 194LINQ to SQL and LINQ to Entities 194LINQ to DataSet 195

PLInQ 198summary 200exercises 201

ChAPtER 9: ERROR hANdLING 205

Bugs Versus Undesirable conditions 206Catching Bugs 206Code Contracts 209Catching Undesirable Conditions 213Global Exception Handling 216

try catch Blocks 220Exception Objects 223Throwing Exceptions 224Rethrowing Exceptions 226Custom Exceptions 227

summary 229exercises 229

ChAPtER 10: tRACING ANd dEbuGGING 231

The Debug menu 232The Debug ➪ Windows submenu 234The Breakpoints Window 235The Immediate Window 237Trace Listeners 238summary 240exercises 241

Page 22: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

xx

CONTENTS

PARt III: ObjECt-ORIENtEd PROGRAMMING

ChAPtER 11: OOP CONCEPtS 245

classes 245encapsulation 248Inheritance 250

Inheritance Hierarchies 251Refinement and Abstraction 252 Has-a and Is-a Relationships 257Adding and Modifying Class Features 257Hiding and Overriding 258abstract 261sealed 262

Polymorphism 263summary 266exercises 266

ChAPtER 12: CLASSES ANd StRuCtuRES 269

classes 270attributes 270accessibility 271abstract | sealed | static 272partial 273

structures 275Value Versus Reference Types 275Memory Requirements 276Heap and Stack Performance 277Object Assignment 277Parameter Passing 277Boxing and Unboxing 281

constructors 282structure Instantiation Details 285garbage collection 286

Destructors 286Dispose 288

events 290Declaring Events 290Raising Events 292Catching Events 292Using Event Delegate Types 292Using Static Events 296

Page 23: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

xxi

CONTENTS

Hiding and Overriding Events 296Raising Parent Class Events 296Implementing Custom Events 297

static methods 298summary 300exercises 301

ChAPtER 13: NAMESPACES 303

collisions in .neT 304The using Directive 304

Project Templates 307Item Templates 309

The Default namespace 311making namespaces 311resolving namespaces 313The global namespace 314summary 315exercises 315

ChAPtER 14: COLLECtION CLASSES 317

arrays 318Dimensions 318Lower Bounds 318Resizing 319Speed 320Other Array Class Features 320

system.collections 321ArrayList 321StringCollection 324NameValueCollection 325

Dictionaries 326ListDictionary 327Hashtable 328HybridDictionary 329StringDictionary 329SortedList 329

collectionsUtil 331stacks and Queues 331

Stack 331Queue 333

Page 24: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

xxii

CONTENTS

generic collections 335collection Initializers 337Iterators 338summary 339exercises 340

ChAPtER 15: GENERICS 343

advantages of generics 344Defining generics 344

Generic Constructors 345Multiple Types 346Constrained Types 348Default Values 352

Instantiating generic classes 352generic collection classes 352generic methods 352generics and extension methods 353summary 354exercises 355

PARt IV: INtERACtING wIth thE ENVIRONMENt

ChAPtER 16: PRINtING 359

Windows forms Printing 359Basic Printing 360Drawing Basics 365

WPf Printing 380Using a Paginator 381Creating Documents 385

summary 390exercises 390

ChAPtER 17: CONFIGuRAtION ANd RESOuRCES 393

environment Variables 394Setting Environment Variables 394Using System .Environment 395

registry 397configuration files 402

Page 25: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

xxiii

CONTENTS

resource files 405Application Resources 405Embedded Resources 406Localization Resources 407

summary 408exercises 408

ChAPtER 18: StREAMS 411

stream 412filestream 414memorystream 415Binaryreader and BinaryWriter 416Textreader and TextWriter 418stringreader and stringWriter 419streamreader and streamWriter 421exists, openText, createText, and appendText 422custom stream classes 423summary 423exercises 424

ChAPtER 19: FILE SyStEM ObjECtS 425

filesystem Permissions 426.neT framework classes 426

Directory 426File 428DriveInfo 430DirectoryInfo 431FileInfo 432FileSystemWatcher 434Path 436

Using the recycle Bin 438Using the FileIO .FileSystem Class 438Using API Functions 439Using Shell32 .Shell 440

summary 443exercises 444

Page 26: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

xxiv

CONTENTS

ChAPtER 20: NEtwORKING 445

networking classes 446Downloading Information 448

Downloading with WebClient 448Downloading with WebRequest 451

Uploading Information 455Uploading with WebClient 455Uploading with WebRequest 455

getting fTP Information 456sending e-mail 458sending Text messages 460summary 462exercises 463

PARt V: AdVANCEd tOPICS

ChAPtER 21: REGuLAR ExPRESSIONS 469

Building regular expressions 470Character Escapes 471Character Classes 472Anchors 473Grouping Constructs 474Quantifiers 475Alternation Constructs 476Sample Regular Expressions 476

Using regular expressions 478Matching Patterns 479Finding Matches 480Making Replacements 481Parsing Input 482

summary 483exercises 483

ChAPtER 22: PARALLEL PROGRAMMING 485

Interacting with the User Interface 488BackgroundWorker 491

TPL 492Parallel .For 492Parallel .ForEach 494Parallel .Invoke 495

Page 27: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

xxv

CONTENTS

Tasks 496Threads 498coordinating Tasks 499

Race Conditions 499Deadlocks 501

Thread-safe objects 503summary 504exercises 505

ChAPtER 23: AdO.NEt 509

selecting a Database 510Using Bound controls 511

Making a Data Source 511Making a DataGridView Interface 516Making a Details Interface 518Making a DataGrid Interface 518

Loading Datasets 525Using aDo.neT 527summary 530exercises 531

ChAPtER 24: xML 533

Basic XmL syntax 534Writing XmL Data 538

XmlWriter 538Document Object Model 541XML Literals 547

reading XmL Data 547XmlTextReader 547Document Object Model 550

related Technologies 551XPath 552XSLT 555

summary 559exercises 559

ChAPtER 25: SERIALIzAtION 563

XmL serialization 564Performing Serialization 565Controlling Serialization 569

Page 28: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

xxvi

CONTENTS

Json serialization 573Performing Serialization 574Controlling Serialization 575

Binary serialization 576summary 578exercises 578

ChAPtER 26: REFLECtION 581

Learning about classes 582getting and setting Properties 585getting assembly Information 589Invoking methods 591running scripts 593summary 597exercises 597

ChAPtER 27: CRyPtOGRAPhy 601

cryptographic operations 602randomness 603

Using Random Numbers for Encryption 604Using Encryption for Random Numbers 604Cryptographically Secure Randomness 604Generating Random Numbers 605

symmetric Key encryption 608Simple Encryption and Decryption 608Keys and Initialization Vectors 612Generating Key and IV Values 613

asymmetric Key encryption 614Creating, Saving, and Retrieving Keys 615Encrypting Data 616Decrypting Data 616Example Encryption 617

summary 619exercises 619

PARt VI: APPENdICES

APPENdIx A: SOLutIONS tO ExERCISES 625

chapter 1 625chapter 2 626

Page 29: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

xxvii

CONTENTS

chapter 3 627chapter 4 629chapter 5 631chapter 6 635chapter 7 638chapter 8 642chapter 9 648chapter 10 655chapter 11 659chapter 12 665chapter 13 667chapter 14 668chapter 15 673chapter 16 678chapter 17 682chapter 18 685chapter 19 689chapter 20 694chapter 21 702chapter 22 706chapter 23 711chapter 24 713chapter 25 720chapter 26 725chapter 27 728

APPENdIx b: dAtA tyPES 733

casting and converting Values 734Widening and Narrowing Conversions 735Converting Objects 735The as Operator 735Casting Arrays 736

Parsing Values 736

APPENdIx C: VARIAbLE dECLARAtIONS 737

Initialization expressions 738Using 739enumerated Type Declarations 739

Page 30: C# 5.0 PROGRAMMER’S REFERENCE...c# 5.0 Programmer’s r eference Published by John Wiley & Sons, Inc. ... DateTime and Timespan operations 111 operator overloading 112 Comparison

xxviii

CONTENTS

APPENdIx d: CONStANt dECLARAtIONS 741

APPENdIx E: OPERAtORS 743

arithmetic operators 743comparison operators 744Logical operators 744Bitwise operators 745assignment operators 745conditional and null-coalescing operators 745operator Precedence 745DateTime and Timespan operators 747operator overloading 748

APPENdIx F: MEthOd dECLARAtIONS 749

methods 749Property Procedures 750Lambda functions and expressions 750extension methods 751

APPENdIx G: uSEFuL AttRIbutES 753

Useful XmL serialization attributes 753Useful Json serialization attributes 754Binary serialization attributes 754other Useful attributes 755

APPENdIx h: CONtROL StAtEMENtS 757

Decision statements 757if-else Statements 757switch 757Conditional and Null-coalescing Operators 758

Looping statements 758for Loops 758while Loops 759do Loops 759foreach Loops 759Enumerators 760Iterators 760break and continue Statements 760