PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2...

30

Transcript of PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2...

Page 1: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET
Page 2: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET
Page 3: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

PROFESSIONAL C# 7 AND .NET CORE 2.0

INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . liii

▸ PART I THE C# LANGUAGE

ChAPTER 1 .NET Applications and Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

ChAPTER 2 Core C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

ChAPTER 3 Objects and Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

ChAPTER 4 Object-Oriented Programming with C# . . . . . . . . . . . . . . . . . . . . . 109

ChAPTER 5 Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

ChAPTER 6 Operators and Casts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151

ChAPTER 7 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193

ChAPTER 8 Delegates, Lambdas, and Events . . . . . . . . . . . . . . . . . . . . . . . . . . . 215

ChAPTER 9 Strings and Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . 235

ChAPTER 10 Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255

ChAPTER 11 Special Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287

ChAPTER 12 Language Integrated Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305

ChAPTER 13 Functional Programming with C# . . . . . . . . . . . . . . . . . . . . . . . . . . 343

ChAPTER 14 Errors and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367

ChAPTER 15 Asynchronous Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391

ChAPTER 16 Reflection, Metadata, and Dynamic Programming . . . . . . . . . . . . . 411

ChAPTER 17 Managed and Unmanaged Memory . . . . . . . . . . . . . . . . . . . . . . . . 439

ChAPTER 18 Visual Studio 2017 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479

▸ PART II .NET CORE AND THE WINDOWS RUNTIME

ChAPTER 19 Libraries, Assemblies, Packages, and NuGet . . . . . . . . . . . . . . . . . 539

ChAPTER 20 Dependency Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559

ChAPTER 21 Tasks and Parallel Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . 583

ChAPTER 22 Files and Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631

Continues

Page 4: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

ChAPTER 23 Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669

ChAPTER 24 Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713

ChAPTER 25 ADO.NET and Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 741

ChAPTER 26 Entity Framework Core . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 769

ChAPTER 27 Localization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 831

ChAPTER 28 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 863

ChAPTER 29 Tracing, Logging, and Analytics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895

▸ PART III WEB APPLICATIONS AND SERVICES

ChAPTER 30 ASP.NET Core . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 923

ChAPTER 31 ASP.NET Core MVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 963

ChAPTER 32 Web API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1039

▸ PART IV APPS

ChAPTER 33 Windows Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1083

ChAPTER 34 Patterns with XAML Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1157

ChAPTER 35 Styling Windows Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1195

ChAPTER 36 Advanced Windows Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1239

ChAPTER 37 Xamarin.Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1291

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1327

▸ ONLINE CHAPTERS

BONUS ChAPTER 1 Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . OC1

BONUS ChAPTER 2 XML and JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . OC33

BONUS ChAPTER 3 WebHooks and SignalR . . . . . . . . . . . . . . . . . . . . . . . . . . OC71

BONUS ChAPTER 4 Bots and Cognitive Services . . . . . . . . . . . . . . . . . . . . . . . OC99

BONUS ChAPTER 5 More Windows Apps Features . . . . . . . . . . . . . . . . . . . . OC123

Page 5: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

PROFESSIONAL

C# 7 and .NET Core 2.0

Page 6: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET
Page 7: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

PROFESSIONAL

C# 7 and .NET Core 2.0

Christian Nagel

Page 8: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

Professional C# 7 and .NET Core 2.0

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

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

Published simultaneously in Canada

ISBN: 978-1-119-44927-0 ISBN: 978-1-119-44924-9 (ebk) ISBN: 978-1-119-44926-3 (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:// booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.

Library of Congress Control Number: 2018931434

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trade-marks 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 9: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

This book is dedicated to my family—Angela,

Stephanie, Matthias, and Katharina—I love you all!

Page 10: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET
Page 11: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

ABOUT ThE AUThOR

ChRISTIAN NAGEL is Microsoft MVP for Visual Studio and Development Technologies and has been Microsoft Regional Director for more than 15 years. Christian founder of CN innovation, where he offers coaching, training, code reviews, and assistance with architecting and developing solutions using Microsoft technologies. He draws on more than 25 years of software development experience.

Christian started his computing career with PDP 11 and VAX/VMS systems at Digital Equipment Corporation, covering a variety of languages and platforms. Since 2000, when .NET was just a technology preview, he has been working with various technolo-gies to build .NET solutions. Currently, he mainly coaches people on development and

architecting Windows apps, ASP.NET Core web applications, and Xamarin and helps them use several Microsoft Azure service offerings.

Even after many years in software development, Christian still loves learning and using new technologies and teaching others how to use the new technologies in various forms. Using his profound knowledge of Microsoft technologies, he has written numerous books and is certified as Microsoft Certified Trainer and Certified Solution Developer. Christian speaks at international conferences such as Microsoft Ignite (previ-ously named TechEd), BASTA! and TechDays. He founded INETA Europe to support .NET user groups. You can contact Christian via his website www.cninnovation.com, read his blog at https://csharp .christiannagel.com, and follow his tweets at @christiannagel.

Page 12: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET
Page 13: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

ABOUT ThE TEChNICAL EDITOR

ISTVÁN NOVÁK is an associate and the chief technology consultant with SoftwArt, a small Hungarian IT consulting company. He works as a software architect and com-munity evangelist. In the last 25 years, he has participated in more than 50 enterprise software development projects. In 2002, he co-authored the first Hungarian book about .NET development. In 2007, he was awarded the Microsoft Most Valuable Professional (MVP) title, and in 2011 he became a Microsoft Regional Director. István co-authored Visual Studio 2010 and .NET 4 Six-in-One (Wiley, 2010) and Beginning Windows 8 Application Development (Wiley, 2012), and he authored Beginning Visual Studio LightSwitch Development (Wiley, 2011). István holds a master’s degree from the Technical University of Budapest, Hungary and also has a doctoral degree in software

technology. He lives in Dunakeszi, Hungary, with his wife and two daughters. He is a passionate scuba diver. You may have a good chance of meeting him underwater at the Red Sea in any season of the year.

Page 14: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET
Page 15: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

SENIOR ACQUISITIONS EDITORKenyon Brown

PROJECT EDITORCharlotte Kughen

TEChNICAL EDITORIstván Novák

PRODUCTION EDITORAthiyappan Lalith Kumar

COPY EDITORCharlotte Kughen

MANAGER OF CONTENT DEVELOPMENT AND ASSEMBLYPete Gaughan

PRODUCTION MANAGERKathleen Wisor

MARKETING MANAGERChristie Hilbrich

BUSINESS MANAGERAmy Knies

EXECUTIVE EDITORJim Minatel

PROJECT COORDINATOR, COVERBrent Savage

PROOFREADERNancy Bell

INDEXERNancy Guenther

COVER DESIGNERWiley

COVER IMAGE© Henrik5000/Getty Images

CREDITS

Page 16: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET
Page 17: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

ACKNOWLEDGMENTS

I WANT TO ThANK Charlotte Kughen, who made my text so much more readable. Often I was working late at night writing while .NET Core was continuously evolving. Charlotte was of enormous help to change my ideas into great readable text. She also invested many weekends to help bring this book out fast. Special thanks also goes to István Novák, who has authored several great books. Despite all the issues we had with the fast evolving .NET Core and the interim builds I was using while working on the book, István chal-lenged me to enhance the code samples that allow you—the reader—to better follow the flow. Thank you, Charlotte and István—you’ve been of great help for the quality of this book.

I also would like to thank Richard Lander from the .NET Core team. We had a great discussion in Redmond on the content and directions for the 11th edition of the book. Rich also found the time to give me good advice on a few chapters of the book.

I also would like to thank Kenyon Brown and everyone else at Wiley who helped to get edition 11 of this great book published. I also want to thank my wife and children for supporting my writing. You’ve been enormously helpful and understanding while I was working on the book for many nights, weekends, and winter holidays. Angela, Stephanie, Matthias, and Katharina—you are my loved ones. This would not have been possible without you.

Page 18: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET
Page 19: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

CONTENTS

INTRODUCTION liii

ParT I: THE C# LaNGUaGE

CHaPTEr 1: .NET aPPLICaTIONS aND TOOLS 3

Choosing Your Technologies 3Reviewing .NET History 4

C# 1.0—A New Language 5C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7C# 3 and .NET 3.5—LINQ 7C# 4 and .NET 4—Dynamic and TPL 8C# 5 and Asynchronous Programming 8C# 6 and .NET Core 1.0 9C# 7 and .NET Core 2.0 10Choosing Technologies and Going Forward 11

.NET Terms 12.NET Framework 13.NET Core 13.NET Standard 14NuGet Packages 14Namespaces 15Common Language Runtime 16Windows Runtime 17

Using the .NET Core CLI 18Setting Up the Environment 18Creating the Application 19Building the Application 20Running the Application 20Creating a Web Application 21Publishing the Application 22Self-Contained Deployments 23

Using Visual Studio 2017 24Installing Visual Studio 2017 24Creating a Project 24Working with Solution Explorer 25Configuring Project Properties 26

Page 20: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

xviii

CONTENTS

Getting to Know the Editor 28Building a Project 28Running an Application 29Debugging 29

Application Types and Technologies 29Data Access 30Windows Apps 30Xamarin 30Web Applications 31Web API 31WebHooks and SignalR 32Microsoft Azure 32

Software as a Service 32Infrastructure as a Service 32Platform as a Service 33Functions as a Service 33

Developer Tools 33Visual Studio Community 33Visual Studio Professional 34Visual Studio Enterprise 34Visual Studio for Mac 34Visual Studio Code 34

Summary 35

CHaPTEr 2: COrE C# 37

Fundamentals of C# 38Hello, World! 38

Working with Variables 39Initializing Variables 40Using Type Inference 41Understanding Variable Scope 42

Scope Clashes for Local Variables 42Scope Clashes for Fields and Local Variables 43

Working with Constants 44Using Predefined Data Types 44

Value Types and Reference Types 44.NET Types 46Predefined Value Types 46

Integer Types 46Digit Separators 47Working with Binary Values 47Floating-Point Types 48

Page 21: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

xix

CONTENTS

The Decimal Type 48The Boolean Type 49The Character Type 49Literals for Numbers 50

Predefined Reference Types 50The object Type 50The string Type 51

Controlling Program Flow 52Conditional Statements 52

The if Statement 52The switch Statement 54

Loops 56The for Loop 56The while Loop 57The do. . .while Loop 58The foreach Loop 58

Jump Statements 58The goto Statement 59The break Statement 59The continue Statement 59The return Statement 59

Getting Organized with Namespaces 59The using Directive 60Namespace Aliases 61

Understanding the Main Method 62Using Comments 63

Internal Comments Within the Source Files 63XML Documentation 64

Understanding C# Preprocessor Directives 65#define and #undef 65#if, #elif, #else, and #endif 66#warning and #error 67#region and #endregion 67#line 67#pragma 68

C# Programming Guidelines 68Rules for Identifiers 68Usage Conventions 69Naming Conventions 70

Casing of Names 71Name Styles 71Namespace Names 71Names and Keywords 72

Page 22: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

xx

CONTENTS

Use of Properties and Methods 72Use of Fields 73

Summary 73

CHaPTEr 3: OBJECTS aND TYPES 75

Creating and Using Classes 76Classes and Structs 76Classes 77

Fields 78Readonly Fields 78Properties 79

Expression-Bodied Property Accessors 80Auto-Implemented Properties 80Access Modifiers for Properties 81Read-Only Properties 82Auto-Implemented Read-Only Properties 82Expression-Bodied Properties 82Immutable Types 83

Anonymous Types 83Methods 84

Declaring Methods 84Expression-Bodied Methods 84Invoking Methods 84Method Overloading 85Named Arguments 86Optional Arguments 86Variable Number of Arguments 87

Constructors 88Expression Bodies with Constructors 90Calling Constructors from Other Constructors 90Static Constructors 91

Structs 92Structs Are Value Types 94Readonly structs 95Structs and Inheritance 95Constructors for Structs 96ref structs 96

Passing Parameters by Value and by Reference 96ref Parameters 97out Parameters 98in Parameters 99

Page 23: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

xxi

CONTENTS

Nullable Types 100Enum Types 101Partial Classes 103Extension Methods 105The Object Class 106Summary 107

CHaPTEr 4: OBJECT-OrIENTED PrOGraMMING WITH C# 109

Object Orientation 109Types of Inheritance 110

Multiple Inheritance 110Structs and Classes 110

Implementation Inheritance 110Virtual Methods 111Polymorphism 113Hiding Methods 113Calling Base Versions of Methods 115Abstract Classes and Methods 115Sealed Classes and Methods 116Constructors of Derived Classes 117

Modifiers 119Access Modifiers 119Other Modifiers 120

Interfaces 121Defining and Implementing Interfaces 122Interface Inheritance 124

Is and as Operators 126Summary 127

CHaPTEr 5: GENErICS 129

Generics Overview 129Performance 130Type Safety 131Binary Code Reuse 131Code Bloat 132Naming Guidelines 132

Creating Generic Classes 132Generics Features 135

Default Values 136Constraints 136Inheritance 138Static Members 139

Page 24: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

xxii

CONTENTS

Generic Interfaces 139Covariance and Contra-Variance 140Covariance with Generic Interfaces 141Contra-Variance with Generic Interfaces 142

Generic Structs 143Generic Methods 145

Generic Methods Example 145Generic Methods with Constraints 146Generic Methods with Delegates 147Generic Methods Specialization 147

Summary 149

CHaPTEr 6: OPEraTOrS aND CaSTS 151

Operators and Casts 152Operators 152

Operator Shortcuts 153The Conditional-Expression Operator (?:) 154The checked and unchecked Operators 155The is Operator 156The as Operator 156The sizeof Operator 157The typeof Operator 158The nameof Operator 158The index Operator 158Nullable Types and Operators 159The Null Coalescing Operator 160The Null-Conditional Operator 160Operator Precedence and Associativity 161

Using Binary Operators 163Shifting Bits 165Signed and Unsigned Numbers 165

Type Safety 167Type Conversions 167

Implicit Conversions 167Explicit Conversions 169

Boxing and Unboxing 171Comparing Objects for Equality 171

Comparing Reference Types for Equality 171The ReferenceEquals Method 172The Virtual Equals Method 172The Static Equals Method 172

Page 25: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

xxiii

CONTENTS

Comparison Operator (==) 172Comparing Value Types for Equality 173

Operator Overloading 173How Operators Work 174Operator Overloading Example: The struct Vector 175Overloading the Comparison Operators 178Which Operators Can You Overload? 180

Implementing Custom Index Operators 181User-Defined Casts 183

Implementing User-Defined Casts 184Casts Between Classes 187Casts Between Base and Derived Classes 188Boxing and Unboxing Casts 189

Multiple Casting 189Summary 192

CHaPTEr 7: arraYS 193

Multiple Objects of the Same Type 194Simple Arrays 194

Array Declaration 194Array Initialization 194Accessing Array Elements 195Using Reference Types 196

Multidimensional Arrays 197Jagged Arrays 198Array Class 198

Creating Arrays 199Copying Arrays 199Sorting 200

Arrays as Parameters 203Array Covariance 203Enumerators 203

IEnumerator Interface 204foreach Statement 204yield Statement 205

Different Ways to Iterate Through Collections 206Returning Enumerators with Yield Return 207

Structural Comparison 209Spans 210

Creating Slices 211Changing Values Using Spans 212ReadOnly Spans 212

Page 26: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

xxiv

CONTENTS

Array Pools 213Creating the Array Pool 213Renting Memory from the Pool 213Returning Memory to the Pool 214

Summary 214

CHaPTEr 8: DELEGaTES, LaMBDaS, aND EVENTS 215

Referencing Methods 215Delegates 216

Declaring Delegates 217Using Delegates 218Simple Delegate Example 220Action<T> and Func<T> Delegates 222BubbleSorter Example 222Multicast Delegates 225Anonymous Methods 228

Lambda Expressions 229Parameters 229Multiple Code Lines 230Closures 230

Events 231Event Publisher 231Event Listener 233

Summary 234

CHaPTEr 9: STrINGS aND rEGULar EXPrESSIONS 235

Examining System.String 236Building Strings 237StringBuilder Members 240

String Formats 241String Interpolation 241

FormattableString 241Using Other Cultures with String Interpolation 242Escaping Curly Brackets 242

DateTime and Number Formats 243Custom String Formats 244

Regular Expressions 245Introduction to Regular Expressions 245The RegularExpressionsPlayground Example 246

Page 27: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

xxv

CONTENTS

Displaying Results 250Matches, Groups, and Captures 251

Strings and Spans 253Summary 254

CHaPTEr 10: COLLECTIONS 255

Overview 255Collection Interfaces and Types 256Lists 257

Creating Lists 258Collection Initializers 258Adding Elements 259Inserting Elements 260Accessing Elements 260Removing Elements 260Searching 261Sorting 263Read-Only Collections 264

Queues 265Stacks 268Linked Lists 270Sorted List 274Dictionaries 276

Dictionary Initializers 276Key Type 276Dictionary Example 278Lookups 281Sorted Dictionaries 282

Sets 282Performance 284Summary 286

CHaPTEr 11: SPECIaL COLLECTIONS 287

Overview 287Working with Bits 287

BitArray 288BitVector32 290

Observable Collections 292Immutable Collections 294

Using Builders with Immutable Collections 295

Page 28: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

xxvi

CONTENTS

Immutable Collection Types and Interfaces 296Using LINQ with Immutable Arrays 297

Concurrent Collections 297Creating Pipelines 298Using a BlockingCollection 301Using a ConcurrentDictionary 302Completing the Pipeline 303

Summary 304

CHaPTEr 12: LaNGUaGE INTEGraTED QUErY 305

LINQ Overview 305Lists and Entities 306LINQ Query 308Extension Methods 309Deferred Query Execution 311

Standard Query Operators 313Filtering 314Filtering with Index 315Type Filtering 316Compound from 316Sorting 317Grouping 319Variables Within the LINQ Query 320Grouping with Nested Objects 320Inner Join 322Left Outer Join 324Group Join 325Set Operations 329Zip 330Partitioning 331Aggregate Operators 332Conversion Operators 333Generation Operators 335

Parallel LINQ 335Parallel Queries 335Partitioners 336Cancellation 337

Expression Trees 338LINQ Providers 340Summary 341

Page 29: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

xxvii

CONTENTS

CHaPTEr 13: FUNCTIONaL PrOGraMMING WITH C# 343

What Is Functional Programming? 343Avoiding State Mutation 344Functions as First Class 345

Higher-Order Functions 345Pure Functions 346

Expression-Bodied Members 346Extension Methods 347Using Static 348Local Functions 350

Local Functions with the yield Statement 351Recursive Local Functions 353

Tuples 354Declaring and Initializing Tuples 355Tuple Deconstruction 356Returning Tuples 356Behind the Scenes 357Compatibility of ValueTuple with Tuple 358Infer Tuple Names 359Tuples with Linked Lists 360Tuples with LINQ 360Deconstruction 361Deconstruction with Extension Methods 362

Pattern Matching 362Pattern Matching with the is Operator 363Pattern Matching with the switch Statement 365Pattern Matching with Generics 365

Summary 366

CHaPTEr 14: ErrOrS aND EXCEPTIONS 367

Introduction 367Exception Classes 368Catching Exceptions 370

Exceptions and Performance 372Implementing Multiple Catch Blocks 372Catching Exceptions from Other Code 375System.Exception Properties 376Exception Filters 377Re-throwing Exceptions 377

Naïve Use to Rethrow the Exception 379Changing the Exception 379

Page 30: PROFESSIONAL...Choosing Your Technologies 3 Reviewing .NET History 4 C# 1.0—A New Language 5 C# 2 and .NET 2 with Generics 6.NET 3—Windows Presentation Foundation 7 C# 3 and .NET

xxviii

CONTENTS

Rethrowing the Exception 380Using Filters to Add Functionality 380

What Happens If an Exception Isn’t Handled? 381User-Defined Exception Classes 382

Catching the User-Defined Exceptions 382Throwing the User-Defined Exceptions 384Defining the User-Defined Exception Classes 387

Caller Information 389Summary 390

CHaPTEr 15: aSYNCHrONOUS PrOGraMMING 391

Why Asynchronous Programming Is Important 391.NET History of Asynchronous Programming 392

Synchronous Call 393Asynchronous Pattern 393Event-Based Asynchronous Pattern 394Task-Based Asynchronous Pattern 395Async Main Method 396

Foundation of Asynchronous Programming 396Creating Tasks 397Calling an Asynchronous Method 397Using the Awaiter 398Continuation with Tasks 399Synchronization Context 399Using Multiple Asynchronous Methods 400

Calling Asynchronous Methods Sequentially 400Using Combinators 400

Using ValueTasks 401Converting the Asynchronous Pattern 402

Error Handling 403Handling Exceptions with Asynchronous Methods 403Handling Exceptions with Multiple Asynchronous Methods 404Using AggregateException Information 405

Async with Windows Apps 405Configure Await 406Switch to the UI Thread 407Using IAsyncOperation 408Avoid Blocking Scenarios 408

Summary 409