Table Of ContentC
o 7
v t
er h
s . E
d
N i
E ti
T o
S
t n
a
n
d
a
r
d
2
C# 7.0
in a Nutshell
THE DEFINITIVE REFERENCE
Joseph Albahari & Ben Albahari
C# 7.0
IN A NUTSHELL
Joseph Albahari and Ben Albahari
C# 7.0 in a Nutshell
by Joseph Albahari and Ben Albahari
Copyright © 2018 Joseph Albahari, Ben Albahari. 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://oreilly.com/safari). For more information,
contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com.
Editors: Rachel Roumeliotis Indexer: Judith McConville
Production Editor: Colleen Cole Interior Designer: David Futato
Copyeditor: Jasmine Kwityn Cover Designer: Karen Montgomery
Proofreader: Kim Cofer Illustrator: Rebecca Demarest
October 2017: First Edition
Revision History for the First Edition
2017-10-03: First Release
2017-11-03: Second Release
See http://oreilly.com/catalog/errata.csp?isbn=9781491987650 for release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. C# 7.0 in a Nutshell, the
cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the authors have used good faith efforts to ensure that the informa‐
tion and instructions contained in this work are accurate, the publisher and the authors dis‐
claim all responsibility for errors or omissions, including without limitation responsibility for
damages resulting from the use of or reliance on this work. Use of the information and
instructions contained in this work is at your own risk. If any code samples or other technol‐
ogy this work contains or describes is subject to open source licenses or the intellectual prop‐
erty rights of others, it is your responsibility to ensure that your use thereof complies with
such licenses and/or rights.
978-1-491-98765-0
[M]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
1. Introducing C# and the .NET Framework. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Object Orientation 1
Type Safety 2
Memory Management 3
Platform Support 3
C# and the CLR 3
The CLR and .NET Framework 4
Other Frameworks 5
A Brief History of C# 8
2. C# Language Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
A First C# Program 15
Syntax 18
Type Basics 21
Numeric Types 30
Boolean Type and Operators 37
Strings and Characters 39
Arrays 42
Variables and Parameters 46
Expressions and Operators 56
Null Operators 60
Statements 62
Namespaces 71
3. Creating Types in C#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Classes 79
Inheritance 96
The object Type 105
iii
Structs 109
Access Modifiers 110
Interfaces 112
Enums 118
Nested Types 121
Generics 122
4. Advanced C#. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Delegates 137
Events 146
Lambda Expressions 153
Anonymous Methods 158
try Statements and Exceptions 158
Enumeration and Iterators 167
Nullable Types 173
Extension Methods 179
Anonymous Types 181
Tuples (C# 7) 183
Attributes 186
Caller Info Attributes 188
Dynamic Binding 190
Operator Overloading 198
Unsafe Code and Pointers 201
Preprocessor Directives 205
XML Documentation 207
5. Framework Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
.NET Standard 2.0 215
The CLR and Core Framework 217
Applied Technologies 221
6. Framework Fundamentals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
String and Text Handling 229
Dates and Times 243
Dates and Time Zones 250
Formatting and Parsing 256
Standard Format Strings and Parsing Flags 262
Other Conversion Mechanisms 269
Globalization 273
Working with Numbers 275
Enums 278
The Guid Struct 282
iv | Table of Contents
Equality Comparison 282
Order Comparison 293
Utility Classes 296
7. Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
Enumeration 301
The ICollection and IList Interfaces 309
The Array Class 313
Lists, Queues, Stacks, and Sets 321
Dictionaries 330
Customizable Collections and Proxies 336
Plugging in Equality and Order 343
8. LINQ Queries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
Getting Started 351
Fluent Syntax 353
Query Expressions 360
Deferred Execution 364
Subqueries 370
Composition Strategies 373
Projection Strategies 377
Interpreted Queries 379
LINQ to SQL and Entity Framework 386
Building Query Expressions 400
9. LINQ Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
Overview 409
Filtering 412
Projecting 416
Joining 428
Ordering 436
Grouping 439
Set Operators 442
Conversion Methods 443
Element Operators 446
Aggregation Methods 448
Quantifiers 453
Generation Methods 454
10. LINQ to XML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
Architectural Overview 455
X-DOM Overview 456
Table of Contents | v
Instantiating an X-DOM 460
Navigating and Querying 462
Updating an X-DOM 467
Working with Values 470
Documents and Declarations 473
Names and Namespaces 477
Annotations 482
Projecting into an X-DOM 483
11. Other XML Technologies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
XmlReader 491
XmlWriter 501
Patterns for Using XmlReader/XmlWriter 503
XSD and Schema Validation 507
XSLT 510
12. Disposal and Garbage Collection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
IDisposable, Dispose, and Close 513
Automatic Garbage Collection 519
Finalizers 521
How the Garbage Collector Works 526
Managed Memory Leaks 530
Weak References 534
13. Diagnostics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
Conditional Compilation 539
Debug and Trace Classes 543
Debugger Integration 546
Processes and Process Threads 547
StackTrace and StackFrame 548
Windows Event Logs 550
Performance Counters 553
The Stopwatch Class 558
14. Concurrency and Asynchrony. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
Introduction 559
Threading 560
Tasks 577
Principles of Asynchrony 585
Asynchronous Functions in C# 590
Asynchronous Patterns 606
Obsolete Patterns 614
vi | Table of Contents
15. Streams and I/O. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
Stream Architecture 617
Using Streams 619
Stream Adapters 633
Compression Streams 641
Working with ZIP Files 643
File and Directory Operations 644
File I/O in UWP 654
Memory-Mapped Files 657
Isolated Storage 659
16. Networking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661
Network Architecture 661
Addresses and Ports 664
URIs 665
Client-Side Classes 667
Working with HTTP 680
Writing an HTTP Server 686
Using FTP 689
Using DNS 691
Sending Mail with SmtpClient 692
Using TCP 692
Receiving POP3 Mail with TCP 696
TCP in Windows Runtime 698
17. Serialization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701
Serialization Concepts 701
The Data Contract Serializer 705
Data Contracts and Collections 715
Extending Data Contracts 717
The Binary Serializer 721
Binary Serialization Attributes 723
Binary Serialization with ISerializable 726
XML Serialization 730
18. Assemblies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 741
What’s in an Assembly 741
Strong Names and Assembly Signing 746
Assembly Names 749
Authenticode Signing 752
The Global Assembly Cache 755
Resources and Satellite Assemblies 758
Table of Contents | vii
Resolving and Loading Assemblies 766
Deploying Assemblies Outside the Base Folder 772
Packing a Single-File Executable 773
Working with Unreferenced Assemblies 774
19. Reflection and Metadata. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777
Reflecting and Activating Types 778
Reflecting and Invoking Members 785
Reflecting Assemblies 798
Working with Attributes 799
Dynamic Code Generation 805
Emitting Assemblies and Types 812
Emitting Type Members 816
Emitting Generic Methods and Types 822
Awkward Emission Targets 824
Parsing IL 827
20. Dynamic Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 833
The Dynamic Language Runtime 833
Numeric Type Unification 835
Dynamic Member Overload Resolution 836
Implementing Dynamic Objects 842
Interoperating with Dynamic Languages 845
21. Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849
Code Access Security 849
Identity and Role Security 850
Operating System Security 853
Cryptography Overview 856
Windows Data Protection 856
Hashing 857
Symmetric Encryption 859
Public Key Encryption and Signing 863
22. Advanced Threading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 869
Synchronization Overview 870
Exclusive Locking 870
Locking and Thread Safety 878
Nonexclusive Locking 884
Signaling with Event Wait Handles 889
The Barrier Class 898
Lazy Initialization 899
viii | Table of Contents