Table Of ContentC# 9.0
Pocket
Reference
Instant Help for
C# 9.0 Programmers
Joseph Albahari
& Ben Albahari
C# 9.0 Pocket Reference
Instant Help for C# 9.0
Programmers
Joseph Albahari and Ben Albahari
C# 9.0 Pocket Reference
by Joseph Albahari and Ben Albahari
Copyright © 2021 Joseph Albahari and Ben Albahari. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebasto‐
pol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promo‐
tional use. Online editions are also available for most titles (http://oreilly.com).
For more information, contact our corporate/institutional sales department:
800-998-9938 or [email protected].
Acquisitions Editor: Amanda Quinn
Development Editor: Corbin Collins
Production Editor: Kristen Brown
Copyeditor: Charles Roumeliotis
Proofreader: James Fraleigh
Indexer: WordCo Indexing Services, Inc.
Interior Designer: David Futato
Cover Designer: Karen Montgomery
Illustrator: Kate Dullea
January 2021: First Edition
Revision History for the First Edition
2021-01-13: First Release
See https://oreil.ly/c9pr_1 for release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. C# 9.0
Pocket Reference, the cover image, and related trade dress are trademarks of
O’Reilly Media, Inc.
The views expressed in this work are those of the authors, and do not repre‐
sent the publisher’s views. While the publisher and the authors have used
good faith efforts to ensure that the information and instructions contained
in this work are accurate, the publisher and the authors disclaim all responsi‐
bility for errors or omissions, including without limitation responsibility for
damages resulting from the use of or reliance on this work. Use of the infor‐
mation and instructions contained in this work is at your own risk. If any
code samples or other technology this work contains or describes is subject to
open source licenses or the intellectual property rights of others, it is your
responsibility to ensure that your use thereof complies with such licenses
and/or rights.
978-1-098-10113-8
[LSI]
Table of Contents
C# 9.0 Pocket Reference 1
A First C# Program 2
Syntax 5
Type Basics 8
Numeric Types 19
Boolean Type and Operators 26
Strings and Characters 28
Arrays 32
Variables and Parameters 38
Expressions and Operators 47
Null Operators 53
Statements 55
Namespaces 65
Classes 69
Inheritance 87
The object Type 96
Structs 101
Access Modifiers 103
Interfaces 105
iii
Enums 109
Nested Types 112
Generics 113
Delegates 122
Events 128
Lambda Expressions 134
Anonymous Methods 139
try Statements and Exceptions 140
Enumeration and Iterators 148
Nullable Value Types 154
Nullable Reference Types 158
Extension Methods 160
Anonymous Types 162
Tuples 163
Records (C# 9) 165
Patterns 172
LINQ 176
Dynamic Binding 202
Operator Overloading 210
Attributes 213
Caller Info Attributes 217
Asynchronous Functions 219
Unsafe Code and Pointers 230
Preprocessor Directives 235
XML Documentation 237
Index 241
iv | Table of Contents
C# 9.0 Pocket Reference
C# is a general-purpose, type-safe, primarily object-oriented
programming language, the goal of which is programmer pro‐
ductivity. To this end, the language balances simplicity, expres‐
siveness, and performance. C# 9 is designed to work with the
Microsoft .NET 5 runtime (whereas C# 8 targets .NET Core 3,
and C# 7 targets .NET Core 2 and Microsoft .NET Framework
4.6/4.7/4.8).
NOTE
The programs and code snippets in this book mirror those
in Chapters 2 through 4 of C# 9.0 in a Nutshell and are all
available as interactive samples in LINQPad. Working
through these samples in conjunction with the book accel‐
erates learning in that you can edit the samples and
instantly see the results without needing to set up projects
and solutions in Visual Studio.
To download the samples, click the Samples tab in LINQ‐
Pad and then click “Download more samples.” LINQPad is
free—go to www.linqpad.net.
1
A First C# Program
Following is a program that multiplies 12 by 30 and prints the
result, 360, to the screen. The double forward slash indicates
that the remainder of a line is a comment:
int x = 12 * 30; // Statement 1
System.Console.WriteLine (x); // Statement 2
Our program consists of two statements. Statements in C# exe‐
cute sequentially and are terminated by a semicolon. The first
statement computes the expression 12 * 30 and stores the result
in a variable, named x, whose type is a 32-bit integer (int). The
second statement calls the WriteLine method on a class called
Console, which is defined in a namespace called System. This
prints the variable x to a text window on the screen.
A method performs a function; a class groups function mem‐
bers and data members to form an object-oriented building
block. The Console class groups members that handle
command-line input/output (I/O) functionality, such as the
WriteLine method. A class is a kind of type, which we examine
in “Type Basics” on page 8.
At the outermost level, types are organized into namespaces.
Many commonly used types—including the Console class—
reside in the System namespace. The .NET libraries are organ‐
ized into nested namespaces. For example, the System.Text
namespace contains types for handling text, and System.IO
contains types for input/output.
Qualifying the Console class with the System namespace on
every use adds clutter. The using directive lets you avoid this
clutter by importing a namespace:
using System; // Import the System namespace
int x = 12 * 30;
Console.WriteLine (x); // No need to specify System
A basic form of code reuse is to write higher-level functions
that call lower-level functions. We can refactor our program
2 | C# 9.0 Pocket Reference
with a reusable method called FeetToInches that multiplies an
integer by 12, as follows:
using System;
Console.WriteLine (FeetToInches (30)); // 360
Console.WriteLine (FeetToInches (100)); // 1200
int FeetToInches (int feet)
{
int inches = feet * 12;
return inches;
}
Our method contains a series of statements surrounded by a
pair of braces. This is called a statement block.
A method can receive input data from the caller by specifying
parameters and output data back to the caller by specifying a
return type. Our FeetToInches method has a parameter for
inputting feet, and a return type for outputting inches:
int FeetToInches (int feet)
...
The literals 30 and 100 are the arguments passed to the Feet
ToInches method.
If a method doesn’t receive input, use empty parentheses. If it
doesn’t return anything, use the void keyword:
using System;
SayHello();
void SayHello()
{
Console.WriteLine ("Hello, world");
}
Methods are one of several kinds of functions in C#. Another
kind of function we used in our example program was the *
operator, which performs multiplication. There are also con‐
structors, properties, events, indexers, and finalizers.
A First C# Program | 3
Compilation
The C# compiler compiles source code (a set of files with the .cs
extension) into an assembly. An assembly is the unit of packag‐
ing and deployment in .NET. An assembly can be either an
application or a library. A normal console or Windows applica‐
tion has an entry point, whereas a library does not. The purpose
of a library is to be called upon (referenced) by an application or
by other libraries. .NET 5 itself is a set of libraries (as well as a
runtime environment).
Each of the programs in the preceding section began directly
with a series of statements (called top-level statements). The
presence of top-level statements implicitly creates an entry
point for a console or Windows application. (Without top-level
statements, a Main method denotes an application’s entry point
—see “Custom Type Examples” on page 9.)
To invoke the compiler, you can either use an integrated devel‐
opment environment (IDE) such as Visual Studio or Visual
Studio Code, or call it manually from the command line. To
manually compile a console application with .NET, first down‐
load the .NET 5 SDK, and then create a new project, as follows:
dotnet new console -o MyFirstProgram
cd MyFirstProgram
This creates a folder called MyFirstProgram, which contains a
C# file called Program.cs, which you can then edit. To invoke
the compiler, call dotnet build (or dotnet run, which will
compile and then run the program). The output will be written
to a subdirectory under bin\debug, which will include MyFirst‐
Program.dll (the output assembly) as well as MyFirstPro‐
gram.exe (which runs the compiled program directly).
4 | C# 9.0 Pocket Reference