C# 9 and .NET 5 – Modern Cross-Platform Development - Fifth Edition

4.9 (13 reviews total)
By Mark J. Price
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Hello, C#! Welcome, .NET!

About this book

In C# 9 and .NET 5 – Modern Cross-Platform Development, Fifth Edition, expert teacher Mark J. Price gives you everything you need to start programming C# applications.

This latest edition uses the popular Visual Studio Code editor to work across all major operating systems. It is fully updated and expanded with a new chapter on the Microsoft Blazor framework.

The book’s first part teaches the fundamentals of C#, including object-oriented programming and new C# 9 features such as top-level programs, target-typed new object instantiation, and immutable types using the record keyword. Part 2 covers the .NET APIs, for performing tasks like managing and querying data, monitoring and improving performance, and working with the file system, async streams, serialization, and encryption. Part 3 provides examples of cross-platform apps you can build and deploy, such as websites and services using ASP.NET Core or mobile apps using Xamarin.Forms.

By the end of the book, you will have acquired the understanding and skills you need to use C# 9 and .NET 5 to create websites, services, and mobile apps.

Publication date:
November 2020


Hello, C#! Welcome, .NET!

In this first chapter, the goals are setting up your development environment, understanding the similarities and differences between .NET 5, .NET Core, .NET Framework, and .NET Standard, and then creating the simplest application possible with C# 9 and .NET 5 using Microsoft's Visual Studio Code.

After this first chapter, this book can be divided into three parts: first, the grammar and vocabulary of the C# language; second, the types available in .NET for building app features; and third, examples of common cross-platform apps you can build using C# and .NET.

Most people learn complex topics best by imitation and repetition rather than reading a detailed explanation of the theory; therefore, I will not overload you with detailed explanations of every step throughout this book. The idea is to get you to write some code, build an application from that code, and then for you to see it run.

You don't need to know all the nitty-gritty details immediately. That will be something that comes with time as you build your own apps and go beyond what any book can teach you.

In the words of Samuel Johnson, author of the English dictionary in 1755, I have committed "a few wild blunders, and risible absurdities, from which no work of such multiplicity is free." I take sole responsibility for these and hope you appreciate the challenge of my attempt to lash the wind by writing this book about rapidly evolving technologies like C# and .NET, and the apps that you can build with them.

This first chapter covers the following topics:

  • Setting up your development environment
  • Understanding .NET
  • Building console apps using Visual Studio Code
  • Downloading solution code from a GitHub repository
  • Looking for help

Setting up your development environment

Before you start programming, you'll need a code editor for C#. Microsoft has a family of code editors and Integrated Development Environments (IDEs), which include:

  • Visual Studio Code
  • GitHub Codespaces
  • Visual Studio 2019
  • Visual Studio 2019 for Mac

Using Visual Studio Code for cross-platform development

The most modern and lightweight code editor to choose, and the only one from Microsoft that is cross-platform, is Microsoft Visual Studio Code. It is able to run on all common operating systems, including Windows, macOS, and many varieties of Linux, including Red Hat Enterprise Linux (RHEL) and Ubuntu.

Visual Studio Code is a good choice for modern cross-platform development because it has an extensive and growing set of extensions to support many languages beyond C#, and being cross-platform and lightweight it can be installed on all platforms that your apps will be deployed to for quick bug fixes and so on.

Visual Studio Code is by far the most popular development environment with over half of developers selecting it in the Stack Overflow 2019 survey (the question was not asked in the 2020 survey), as shown in the following chart:

A screenshot of a cell phone

Description automatically generated

Figure 1.1: The most popular development environments

More Information: You can read the survey at the following link: https://insights.stackoverflow.com/survey/2019#development-environments-and-tools

Using Visual Studio Code means a developer can use a cross-platform code editor to develop cross-platform apps. Therefore, I have chosen to use Visual Studio Code for all but the last chapter of this book, because it needs special features not available in Visual Studio Code for building mobile apps.

More Information: You can read about Microsoft's plans for Visual Studio Code at the following link: https://github.com/Microsoft/vscode/wiki/Roadmap

If you prefer to use Visual Studio 2019 or Visual Studio for Mac instead of Visual Studio Code, then of course you can, but I will assume that you are already familiar with how to use them and so I will not give step-by-step instructions for using them in this book. This book does not teach how to use code editors, it teaches how to write code, and that is the same regardless of the tool.

More Information: You can read a comparison of Visual Studio Code and Visual Studio 2019 at the following link: https://www.itworld.com/article/3403683/visual-studio-code-stepping-on-visual-studios-toes.html

Using GitHub Codespaces for development in the cloud

GitHub Codespaces is a fully configured development environment based on Visual Studio Code that can be spun up in an environment hosted in the cloud and accessed through any web browser. It supports Git repos, extensions, and a built-in command-line interface so you can edit, run, and test from any device.

More Information: Read more about GitHub Codespaces at the following link: https://docs.github.com/en/github/developing-online-with-codespaces/about-codespaces

Using Visual Studio 2019 for Windows app development

Microsoft Visual Studio 2019 only runs on Windows, version 7 SP1 or later. You must run it on Windows 10 to create Universal Windows Platform (UWP) apps that are installed from the Windows Store and run in a sandbox to protect your computer. It is the only Microsoft developer tool that can create Windows apps, so we will use it in Appendix B, Building Windows Desktop Apps, which is available as a PDF document at the following link: https://static.packt-cdn.com/downloads/9781800568105_Appendices.pdf.

Using Visual Studio for Mac for mobile development

To compile apps for Apple operating systems like iOS to run on devices like the iPhone and iPad, you must have Xcode, but that tool only runs on macOS. Although you can use Visual Studio 2019 on Windows with its Xamarin extensions to write a cross-platform mobile app, you still need macOS and Xcode to compile it.

So, we will use Visual Studio 2019 for Mac on macOS in Chapter 21, Building Cross-Platform Mobile Apps.

Recommended tools for chapters

To help you to set up the best environment to use in this book, the following table summarizes which tools and operating systems I recommend be used for each of the chapters in this book:



Operating systems

Chapters 1 to 20

Visual Studio Code

Windows, macOS, Linux

Chapter 21

Visual Studio 2019 for Mac


Appendix B

Visual Studio 2019

Windows 10

To write this book, I used my MacBook Pro and the following listed software:

  • Visual Studio Code on macOS as my primary code editor.
  • Visual Studio Code on Windows 10 in a virtual machine to test OS-specific behavior like working with the filesystem.
  • Visual Studio 2019 on Windows 10 in a virtual machine to build Windows apps.
  • Visual Studio 2019 for Mac on macOS to build mobile apps.

More Information: Google and Amazon are supporters of Visual Studio Code, as you can read at the following link: https://www.cnbc.com/2018/12/20/microsoft-cmo-capossela-says-google-employees-use-visual-studio-code.html

Deploying cross-platform

Your choice of code editor and operating system for development does not limit where your code gets deployed.

.NET 5 supports the following platforms for deployment:

  • Windows: Windows 7 SP1, or later. Windows 10 version 1607, or later. Windows Server 2012 R2 SP1, or later. Nano Server version 1809, or later.
  • Mac: macOS High Sierra (version 10.13), or later.
  • Linux: Alpine Linux 3.11, or later. CentOS 7, or later. Debian 9, or later. Fedora 30, or later. Linux Mint 18, or later. openSUSE 15, or later. Red Hat Enterprise Linux (RHEL) 7, or later. SUSE Enterprise Linux 12 SP2, or later. Ubuntu 18.04, 19.10, 20.04, or later.

More Information: You can read the official list of supported operating systems at the following link: https://github.com/dotnet/core/blob/master/release-notes/5.0/5.0-supported-os.md

Windows ARM64 support in .NET 5 and later means you can now develop on and deploy to Windows ARM devices like Microsoft Surface Pro X.

More Information: You can read more about Windows ARM64 support at the following link: https://github.com/dotnet/runtime/issues/36699

Understanding Microsoft Visual Studio Code versions

Microsoft releases a new feature version of Visual Studio Code (almost) every month and bug fix versions more frequently. For example:

  • Version 1.49, August 2020 feature release
  • Version 1.49.1, August 2020 bug fix release

More Information: You can read about the latest versions at the following link: https://code.visualstudio.com/updates

The version used in this book is 1.49 released on September 10, 2020, but the version of Microsoft Visual Studio Code is less important than the version of the C# for Visual Studio Code extension that you will install later.

While the C# extension is not required, it provides IntelliSense as you type, code navigation, and debugging features, so it's something that's very handy to install. To support C# 9, you should install the C# extension version 1.23 or later.

In this book, I will show keyboard shortcuts and screenshots of Visual Studio Code using the macOS version. Visual Studio Code on Windows and variants of Linux are practically identical, although keyboard shortcuts are likely different.

Some common keyboard shortcuts that we will use are shown in the following table:




Show Command Palette

Cmd + Shift + P

Ctrl + Shift + P

Show Command Palette



Go To Definition



Go Back

Ctrl + -

Alt +

Go Forward

Ctrl + Shift + -

Alt +

Show Terminal

Ctrl + ` (backtick)

Ctrl + ' (quote)

New Terminal

Ctrl + Shift + ` (backtick)

Ctrl + Shift + ' (quote)

Toggle Line Comment

Ctrl + /

Ctrl + /

Toggle Block Comment

Shift + Option + A

Shift + Alt + A

I recommend that you download a PDF of keyboard shortcuts for your operating system from the following list:

More Information: You can learn about the default key bindings for Visual Studio Code and how to customize them at the following link: https://code.visualstudio.com/docs/getstarted/keybindings

Visual Studio Code has rapidly improved over the past couple of years and has pleasantly surprised Microsoft with its popularity. If you are brave and like to live on the bleeding edge, then there is an Insiders edition, which is a daily build of the next version.

Downloading and installing Visual Studio Code

Now you are ready to download and install Visual Studio Code, its C# extension, and the .NET 5 SDK:

  1. Download and install either the Stable build or the Insiders edition of Visual Studio Code from the following link: https://code.visualstudio.com/.
  2. Download and install the .NET 5 SDK from the following link: https://www.microsoft.com/net/download.
  3. To install the C# extension, you must first launch the Visual Studio Code application.
  4. In Visual Studio Code, click the Extensions icon or navigate to View | Extensions.
  5. C# is one of the most popular extensions available, so you should see it at the top of the list, or you can enter C# in the search box, as shown in the following screenshot:
    A screenshot of a cell phone

Description automatically generated

    Figure 1.2: The C# extension

  6. Click Install and wait for supporting packages to download and install.

More Information: You can read more about Visual Studio Code support for C# at the following link: https://code.visualstudio.com/docs/languages/csharp

Installing other extensions

In later chapters of this book, you will use more extensions. If you want to install them now, all the extensions that we will use are shown in the following table:



C# for Visual Studio Code (powered by OmniSharp)


C# editing support, including syntax highlighting, IntelliSense, Go to Definition, Find All References, debugging support for .NET, and support for csproj projects on Windows, macOS, and Linux.

MSBuild project tools tinytoy.msbuild-project-tools

Provides IntelliSense for MSBuild project files, including auto-complete for <PackageReference> elements.

C# XML Documentation Comments k--kato.docomment

Generate XML documentation comments.

REST Client


Send an HTTP request and view the response directly in Visual Studio Code.

ILSpy .NET Decompiler


Decompile MSIL assemblies – support for .NET Framework, .NET Core, and .NET Standard.


Understanding .NET

.NET 5, .NET Framework, .NET Core, and Xamarin are related and overlapping platforms for developers used to build applications and services. In this section, I'm going to introduce you to each of these .NET concepts.

Understanding .NET Framework

.NET Framework is a development platform that includes a Common Language Runtime (CLR), which manages the execution of code, and a Base Class Library (BCL), which provides a rich library of classes to build applications from. Microsoft originally designed .NET Framework to have the possibility of being cross-platform, but Microsoft put their implementation effort into making it work best with Windows.

Since .NET Framework 4.5.2 it has been an official component of the Windows operating system. .NET Framework is installed on over one billion computers so it must change as little as possible. Even bug fixes can cause problems, so it is updated infrequently.

All of the apps on a computer written for .NET Framework share the same version of the CLR and libraries stored in the Global Assembly Cache (GAC), which can lead to issues if some of them need a specific version for compatibility.

Good Practice: Practically speaking, .NET Framework is Windows-only and a legacy platform. Do not create new apps using it.

Understanding the Mono and Xamarin projects

Third parties developed a .NET Framework implementation named the Mono project. Mono is cross-platform, but it fell well behind the official implementation of .NET Framework.

More Information: You can read more about the Mono project at the following link: http://www.mono-project.com/

Mono has found a niche as the foundation of the Xamarin mobile platform as well as cross-platform game development platforms like Unity.

More Information: You can read more about Unity at the following link: https://docs.unity3d.com/

Microsoft purchased Xamarin in 2016 and now gives away what used to be an expensive Xamarin extension for free with Visual Studio 2019. Microsoft renamed the Xamarin Studio development tool, which could only create mobile apps, to Visual Studio for Mac and gave it the ability to create other types of projects like console apps and web services. With Visual Studio 2019 for Mac, Microsoft has replaced parts of the Xamarin Studio editor with parts from Visual Studio for Windows to provide closer parity of experience and performance.

Understanding .NET Core

Today, we live in a truly cross-platform world where modern mobile and cloud development have made Windows, as an operating system, much less important. Because of that, Microsoft has been working on an effort to decouple .NET from its close ties with Windows. While rewriting .NET Framework to be truly cross-platform, they've taken the opportunity to refactor and remove major parts that are no longer considered core.

This new product was branded .NET Core and includes a cross-platform implementation of the CLR known as CoreCLR and a streamlined library of classes known as CoreFX.

Scott Hunter, Microsoft Partner Director Program Manager for .NET, has said that "Forty percent of our .NET Core customers are brand-new developers to the platform, which is what we want with .NET Core. We want to bring new people in."

.NET Core is fast-moving and because it can be deployed side by side with an app, it can change frequently, knowing those changes will not affect other .NET Core apps on the same machine. Improvements that Microsoft makes to .NET Core cannot be added to .NET Framework.

More Information: You can read more about Microsoft's positioning of .NET Core and .NET Framework at the following link: https://devblogs.microsoft.com/dotnet/update-on-net-core-3-0-and-net-framework-4-8/

Understanding .NET 5 and the journey to one .NET

At the Microsoft Build developer conference in May 2020, the .NET team announced that their plans for the unification of .NET had been delayed. They said .NET 5 would be released on November 10, 2020 and it would unify all the various .NET platforms except mobile. It will not be until .NET 6 in November 2021 that mobile will also be supported by the unified .NET platform.

.NET Core has been renamed .NET and the major version number has skipped the number four to avoid confusion with .NET Framework 4.x. Microsoft plans on annual major version releases every November, rather like Apple does major version number releases of iOS every September.

More Information: You can read more about Microsoft's plans for the journey to one .NET at the following link: https://devblogs.microsoft.com/dotnet/announcing-net-5-preview-4-and-our-journey-to-one-net/

The following table shows when the key versions of modern .NET were released, when future releases are planned, and which version is used by the various editions of this book:





.NET Core RC1

November 2015


March 2016

.NET Core 1.0

June 2016

.NET Core 1.1

November 2016

.NET Core 1.0.4 and .NET Core 1.1.1

March 2017


March 2017

.NET Core 2.0

August 2017

.NET Core for UWP in Windows 10 Fall Creators Update

October 2017


November 2017

.NET Core 2.1 (LTS)

May 2018

.NET Core 2.2 (Current)

December 2018

.NET Core 3.0 (Current)

September 2019


October 2019

.NET Core 3.1 (LTS)

December 2019

.NET 5.0 (Current)

November 2020


November 2020

.NET 6.0 (LTS)

November 2021


November 2021

Understanding .NET support

.NET versions are either Long-Term Support (LTS) or Current, as described in the following list:

  • LTS releases are stable and require fewer updates over their lifetime. These are a good choice for applications that you do not intend to update frequently. LTS releases will be supported for 3 years after general availability.
  • Current releases include features that may change based on feedback. These are a good choice for applications that you are actively developing because they provide access to the latest improvements. After a 3-month maintenance period, the previous minor version will no longer be supported.

Both receive critical fixes throughout their lifetime for security and reliability. You must stay up to date with the latest patches to get support. For example, if a system is running 1.0 and 1.0.1 has been released, 1.0.1 will need to be installed to get support.

To better understand your choices of Current and LTS releases, it is helpful to see it visually with three-year-long blue bars that do not fade for LTS; and for Current, variable-length green bars that fade to pale green to show the three months after a new release before a Current release reaches end of life, as shown in the following diagram:

A screenshot of a social media post

Description automatically generated

Figure 1.3: Support for various versions

For example, if you create a project using .NET 5.0 and Microsoft releases .NET 5.1 in February 2021, then you will need to upgrade your project to .NET 5.1 by the end of May 2021.

If you need longer-term support from Microsoft, then choose .NET Core 3.1 today, not .NET 5.0. Once .NET 6.0 releases in November 2021, you will still have more than another year of support before you will have to upgrade your project to .NET 6.0.

All versions of .NET Core have reached end of life except the LTS versions that will reach end of life as shown in the following list:

  • .NET Core 2.1 will reach end of life on August 21, 2021.
  • .NET Core 3.1 will reach end of life on December 3, 2022.
  • .NET 6.0 will reach end of life in November 2024 if it releases as planned in November 2021.

More Information: You can read more about .NET Support Policy at the following link: https://dotnet.microsoft.com/platform/support/policy/dotnet-core

Understanding .NET Runtime and .NET SDK versions

.NET Runtime versioning follows semantic versioning, that is, a major increment indicates breaking changes, minor increments indicate new features, and patch increments indicate bug fixes.

.NET SDK versioning does not follow semantic versioning. The major and minor version numbers are tied to the runtime version it is matched with. The patch number follows a convention that indicates the major and minor version of the SDK. You can see an example of this in the following table:




Initial release



SDK bug fix



Runtime and SDK bug fix



SDK new feature



More Information: You can learn more about how versions work at the following link: https://docs.microsoft.com/en-us/dotnet/core/versions/

Removing old versions of .NET

.NET Runtime updates are compatible with a major version such as 5.x and updated releases of the .NET SDK maintain the ability to build applications that target previous versions of the runtime, which enables the safe removal of older versions.

You can see which SDKs and runtimes are currently installed using the following commands:

  • dotnet --list-sdks
  • dotnet --list-runtimes

On Windows, use the App & features section to remove .NET SDKs.

On macOS or Windows, use the dotnet-core-uninstall tool.

More Information: You can read about the .NET Uninstall Tool at the following link: https://docs.microsoft.com/en-us/dotnet/core/additional-tools/uninstall-tool

For example, while writing the fourth edition I used the following command every month:

dotnet-core-uninstall --all-previews-but-latest --sdk

More Information: You can read about removing .NET SDKs and runtimes at the following link: https://docs.microsoft.com/en-us/dotnet/core/install/remove-runtime-sdk-versions.

What is different about .NET Core and .NET 5?

Modern .NET is smaller than the current version of .NET Framework due to the fact that legacy and non-cross-platform technologies have been removed. For example, Windows Forms and Windows Presentation Foundation (WPF) can be used to build graphical user interface (GUI) applications, but they are tightly bound to the Windows ecosystem, so they have been removed from .NET on macOS and Linux.

One of the features of .NET 5 is support for running old Windows Forms and WPF applications using the Windows Desktop Pack that is included with the Windows version of .NET 5, which is why it is bigger than the SDKs for macOS and Linux. You can make some small changes to your legacy Windows app if necessary, and then rebuild it for .NET 5 to take advantage of new features and performance improvements. You'll learn about support for building these types of Windows apps in Appendix B, Building Windows Desktop Apps.

ASP.NET Web Forms and Windows Communication Foundation (WCF) are old web application and service technologies that fewer developers are choosing to use for new development projects today, so they have also been removed from .NET 5. Instead, developers prefer to use ASP.NET MVC and ASP.NET Web API. These two technologies have been refactored and combined into a platform that runs on .NET 5, named ASP.NET Core. You'll learn about the technologies in Chapter 15, Building Websites Using ASP.NET Core Razor Pages, Chapter 16, Building Websites Using the Model-View-Controller Pattern, and Chapter 18, Building and Consuming Web Services.

More Information: Some .NET Framework developers are upset that ASP.NET Web Forms, WCF, and Windows Workflow (WF) are missing from .NET 5 and would like Microsoft to change their minds. There are open source projects to enable WCF and WF to migrate to .NET 5. You can read more at the following link: https://devblogs.microsoft.com/dotnet/supporting-the-community-with-wf-and-wcf-oss-projects/. There is an open source project for Blazor Web Forms components at the following link: https://github.com/FritzAndFriends/BlazorWebFormsComponents

Entity Framework (EF) 6 is an object-relational mapping technology that is designed to work with data that is stored in relational databases such as Oracle and Microsoft SQL Server. It has gained baggage over the years, so the cross-platform API has been slimmed down, has been given support for non-relational databases like Microsoft Azure Cosmos DB, and has been renamed Entity Framework Core. You will learn about it in Chapter 11, Working with Databases Using Entity Framework Core.

If you have existing apps that use the old EF, then version 6.3 is supported on .NET Core 3.0 or later.

More Information: Although .NET 5 has dropped the word Core in its branding, ASP.NET Core and Entity Framework Core will retain the word Core to help differentiate from older legacy versions of those technologies, as explained at the following link: https://docs.microsoft.com/en-us/dotnet/core/dotnet-five

In addition to removing large pieces from .NET Framework in order to make .NET Core, Microsoft has componentized .NET into NuGet packages, those being small chunks of functionality that can be deployed independently.

Microsoft's primary goal is not to make .NET smaller than .NET Framework. The goal is to componentize .NET to support modern technologies and to have fewer dependencies, so that deployment requires only those packages that your application needs.

Understanding .NET Standard

The situation with .NET in 2019 was that there were three forked .NET platforms controlled by Microsoft, as shown in the following list:

  • .NET Core: for cross-platform and new apps
  • .NET Framework: for legacy apps
  • Xamarin: for mobile apps

Each had strengths and weaknesses because they were all designed for different scenarios. This led to the problem that a developer had to learn three platforms, each with annoying quirks and limitations. Because of that, Microsoft defined .NET Standard: a specification for a set of APIs that all .NET platforms could implement to indicate what level of compatibility they have. For example, basic support is indicated by a platform being compliant with .NET Standard 1.4.

With .NET Standard 2.0 and later, Microsoft made all three platforms converge on a modern minimum standard, which made it much easier for developers to share code between any flavor of .NET.

For .NET Core 2.0 and later, this added a number of the missing APIs that developers need to port old code written for .NET Framework to the cross-platform .NET Core. However, some APIs are implemented but throw an exception to indicate to a developer that they should not actually be used! This is usually due to differences in the operating system on which you run .NET. You'll learn how to handle these exceptions in Chapter 2, Speaking C#.

It is important to understand that .NET Standard is just a standard. You are not able to install .NET Standard in the same way that you cannot install HTML5. To use HTML5, you must install a web browser that implements the HTML5 standard.

To use .NET Standard, you must install a .NET platform that implements the .NET Standard specification. .NET Standard 2.0 is implemented by the latest versions of .NET Framework, .NET Core, and Xamarin.

The latest .NET Standard, 2.1, is only implemented by .NET Core 3.0, Mono, and Xamarin. Some features of C# 8.0 require .NET Standard 2.1. .NET Standard 2.1 is not implemented by .NET Framework 4.8 so we should treat .NET Framework as legacy.

Once .NET 6 is released in November 2021, the need for .NET Standard will significantly reduce, because there will be a single .NET for all platforms, including mobile. Even then, apps and websites created for .NET Framework will need to be supported so understanding that you can create .NET Standard 2.0 class libraries that are backward compatible with legacy .NET platforms is important to know.

More Information: .NET Standard versions and which .NET platforms support them are listed at the following link: https://github.com/dotnet/standard/blob/master/docs/versions.md

By the end of 2021, Microsoft promises that there will be a single .NET platform. .NET 6 is planned to have a single BCL and two runtimes: one optimized for server or desktop scenarios like websites and Windows desktop apps based on the .NET Core runtime, and one optimized for mobile apps based on the Xamarin runtime.

.NET platforms and tools used by the book editions

For the first edition of this book, which was written in March 2016, I focused on .NET Core functionality but used .NET Framework when important or useful features had not yet been implemented in .NET Core, because that was before the final release of .NET Core 1.0. Visual Studio 2015 was used for most examples, with Visual Studio Code shown only briefly.

The second edition was (almost) completely purged of all .NET Framework code examples so that readers were able to focus on .NET Core examples that truly run cross-platform.

The third edition completed the switch. It was rewritten so that all of the code was pure .NET Core. But giving step-by-step instructions for both Visual Studio Code and Visual Studio 2019 for all tasks added unnecessary complexity.

The fourth edition continued the trend by only showing coding examples using Visual Studio Code for all but the last two chapters of this book. In Chapter 20, Building Windows Desktop Apps, it used Visual Studio 2019 running on Windows 10, and in Chapter 21, Building Cross-Platform Mobile Apps, it used Visual Studio 2019 for Mac.

In this fifth edition, Chapter 20, Building Windows Desktop Apps, was moved to Appendix B to make space for a new Chapter 20, Building Web User Interfaces Using Blazor. Blazor projects can be created using Visual Studio Code.

In the planned sixth edition, Chapter 21, Building Cross-Platform Mobile and Desktop Apps, will be completely rewritten to show how mobile and desktop cross-platform apps can be created using Visual Studio Code and an extension to support .NET MAUI (Multi-platform App UI). This has to wait until the sixth edition because Microsoft will release .NET MAUI with .NET 6 in November 2021. At that point, the whole book will use Visual Studio Code for all examples.

Understanding intermediate language

The C# compiler (named Roslyn) used by the dotnet CLI tool converts your C# source code into intermediate language (IL) code and stores the IL in an assembly (a DLL or EXE file). IL code statements are like assembly language instructions, which are executed by .NET's virtual machine, known as CoreCLR.

At runtime, CoreCLR loads the IL code from the assembly, the just-in-time (JIT) compiler compiles it into native CPU instructions, and then it is executed by the CPU on your machine. The benefit of this three-step compilation process is that Microsoft is able to create CLRs for Linux and macOS, as well as for Windows. The same IL code runs everywhere because of the second compilation process, which generates code for the native operating system and CPU instruction set.

Regardless of which language the source code is written in, for example, C#, Visual Basic, or F#, all .NET applications use IL code for their instructions stored in an assembly. Microsoft and others provide disassembler tools that can open an assembly and reveal this IL code, such as the ILSpy .NET Decompiler extension.

Comparing .NET technologies

We can summarize and compare .NET technologies in 2020, as shown in the following table:



Host OSes

.NET 5

Modern feature set, full C# 9 support, port existing and create new Windows and Web apps and services.

Windows, macOS, Linux

.NET Framework

Legacy feature set, limited C# 8 support, no C# 9 support, maintain existing applications.

Windows only


Mobile and desktop apps only.

Android, iOS, macOS


Building console apps using Visual Studio Code

The goal of this section is to showcase how to build a console app using Visual Studio Code. Both the instructions and screenshots in this section are for macOS, but the same actions will work with Visual Studio Code on Windows and Linux variants.

The main differences will be native command-line actions such as deleting a file: both the command and the path are likely to be different on Windows or macOS and Linux. Luckily, the dotnet command-line tool will be identical on all platforms.

Writing code using Visual Studio Code

Let's get started writing code!

  1. Start Visual Studio Code.
  2. On macOS, navigate to File | Open.... On Windows, navigate to File | Open Folder…. On both OSes, you can click the Open Folder button in the EXPLORER pane or click the Open folder… link on the Welcome tab, as shown in the following screenshot:
    A screenshot of a cell phone

Description automatically generated

    Figure 1.4: The Visual Studio Code Welcome tab

  3. In the dialog box, navigate to your user folder on macOS (mine is named markjprice), your Documents folder on Windows, or any directory or drive in which you want to save your projects.
  4. Click the New Folder button and name the folder Code.
  5. In the Code folder, create a new folder named Chapter01.
  6. In the Chapter01 folder, create a new folder named HelloCS.
  7. Select the HelloCS folder and on macOS click Open or on Windows click Select Folder.
  8. Navigate to View | Terminal, or on macOS press Ctrl + ` (backtick) and on Windows press Ctrl + ' (single quote). Confusingly, on Windows, the key combination Ctrl + ` (backtick) splits the current window!
  9. In TERMINAL, enter the following command:
    dotnet new console
  10. You will see that the dotnet command-line tool creates a new Console Application project for you in the current folder, and the EXPLORER window shows the two files created, HelloCS.proj and Program.cs, as shown in the following screenshot:
    A screenshot of a cell phone

Description automatically generated

    Figure 1.5: Your EXPLORER window should show both files have been created

  11. In EXPLORER, click on the file named Program.cs to open it in the editor window. The first time that you do this, Visual Studio Code may have to download and install C# dependencies like OmniSharp, the Razor Language Server, and the .NET Core debugger, if it did not do this when you installed the C# extension.
  12. If you see a warning saying that required assets are missing, click Yes, as shown in the following screenshot:
    A screenshot of a cell phone

Description automatically generated

    Figure 1.6: Warning message to add required build and debug assets

  13. After a few seconds, a folder named .vscode will appear in the EXPLORER pane with some files that are used during debugging, as you will learn in Chapter 4, Writing, Debugging, and Testing Functions.
  14. In Program.cs, modify line 9 so that the text that is being written to the console says, Hello, C#!
  15. Navigate to File | Auto Save. This toggle will save the annoyance of remembering to save before rebuilding your application each time.

Compiling and running code using the dotnet CLI

The next task is to compile and run the code.

  1. Navigate to View | Terminal and enter the following command:
    dotnet run
  2. The output in the TERMINAL window will show the result of running your application, as shown in the following screenshot:
    A screenshot of a cell phone

Description automatically generated

    Figure 1.7: The output of running your application

Writing top-level programs

You might be thinking that was a lot of code just to output Hello, C#! Although the boilerplate code is written for you by the project template, is there a simpler way?

Well, in C# 9 there is, and it is known as top-level programs.

Let's compare the traditional minimum console app, as shown in the following code:

using System;
class Program
  static void Main(string[] args)
    Console.WriteLine("Hello World!");

To the new top-level program minimum console app, as shown in the following code:

using System;
Console.WriteLine("Hello World!");

That is a lot simpler, right? If you had to start with a blank file and write all the statements yourself, this is better.

During compilation, all the boilerplate code to define the Program class and its Main method is generated and wrapped around the statements you write. Any using statements still have to go at the top of the file. There can be only one file like this in a project.

Personally, especially when teaching C#, I plan to continue to use the traditional project template since it is true to reality. I am not keen on magic hidden code for the same reason I do not like graphical user interfaces that hide elements in an attempt to simplify the experience but frustrate users because they cannot discover features that they need.

For example, arguments can be passed into a console app. With a top-level program, you would need to know that the args parameter exists even though you cannot see it.


Downloading solution code from the GitHub repository

Git is a commonly used source code management system. GitHub is a company, website, and desktop application that makes it easier to manage Git. Microsoft purchased GitHub in 2018, so it will continue to get closer integration with Microsoft tools.

I used GitHub to store solutions to all the practical exercises that are featured at the end of each chapter. You will find the repository for this chapter at the following link: https://github.com/markjprice/cs9dotnet5.

I recommend that you add the preceding link to your favorite bookmarks because I use the GitHub repository for this book for publishing errata and other useful links.

Using Git with Visual Studio Code

Visual Studio Code has support for Git, but it will use your OS's Git installation, so you must install Git 2.0 or later first before you get these features.

You can install Git from the following link: https://git-scm.com/download.

If you like to use a GUI, you can download GitHub Desktop from the following link:


Cloning the book solution code repository

Let's clone the book solution code repository.

  1. Create a folder named Repos in your user or Documents folder, or wherever you want to store your Git repositories.
  2. In Visual Studio Code, open the Repos folder.
  3. Navigate to View | Terminal, and enter the following command:
    git clone https://github.com/markjprice/cs9dotnet5.git
  4. Note that cloning all of the solutions for all of the chapters will take a minute or so, as shown in the following screenshot:
    A screenshot of a cell phone

Description automatically generated

    Figure 1.8: Cloning the book solution code

More Information: For more information about source code version control with Visual Studio Code, visit the following link: https://code.visualstudio.com/Docs/editor/versioncontrol


Looking for help

This section is all about how to find quality information about programming on the web.

Reading Microsoft documentation

The definitive resource for getting help with Microsoft developer tools and platforms is Microsoft Docs, and you can find it at the following link: https://docs.microsoft.com/.

Getting help for the dotnet tool

At the command line, you can ask the dotnet tool for help with its commands.

  1. To open the official documentation in a browser window for the dotnet new command, enter the following at the command line or in Visual Studio Code Terminal:
    dotnet help new
  2. To get help output at the command line, use the -h or --help flag, as shown in the following command:
    dotnet new console -h
  3. You will see the following partial output:
    Console Application (C#)
    Author: Microsoft
    Description: A project for creating a command-line application that can run on .NET Core on Windows, Linux and macOS
      -f|--framework  The target framework for the project.
                          net5.0           - Target net5.0
                          netcoreapp3.1    - Target netcoreapp3.1
                          netcoreapp3.0    - Target netcoreapp3.0
                      Default: net5.0
      --langVersion   Sets langVersion in the created project file
                      text - Optional
      --no-restore    If specified, skips the automatic restore of the project on create.
                      bool - Optional
                      Default: false / (*) true
    * Indicates the value used if the switch is provided without a value.

Getting definitions of types and their members

One of the most useful keyboard shortcuts in Visual Studio Code is F12 to Go To Definition. This will show what the public definition of the type or member looks like by reading the metadata in the compiled assembly. Some tools, such as ILSpy .NET Decompiler, will even reverse-engineer from the metadata and IL code back into C# for you.

Let's see how to use the Go To Definition feature.

  1. In Visual Studio Code, open the HelloCS folder.
  2. In Program.cs, inside the Main method, enter the following statement to declare an integer variable named z:
    int z;
  3. Click inside int and then press F12, or right-click and choose Go To Definition. In the new code window that appears, you can see how the int data type is defined, as shown in the following screenshot:
    A screenshot of a social media post

Description automatically generated

    Figure 1.9: The int data type

    You can see that int:

    • Is defined using the struct keyword.
    • Is in the System.Runtime assembly.
    • Is in the System namespace.
    • Is named Int32.
    • Is therefore an alias for the System.Int32 type.
    • Implements interfaces such as IComparable.
    • Has constant values for its maximum and minimum values.
    • Has methods like Parse.

    Good Practice: When you try to use Go To Definition, you will sometimes see an error saying No definition found. This is because the C# extension does not know about the current project. Navigate to View | Command Palette, enter and select OmniSharp: Select Project, and then select the correct project that you want to work with.

    Right now, the Go To Definition feature is not that useful to you because you do not yet know what these terms mean.

    By the end of the first part of this book, which teaches you about C#, you will know enough for this feature to become very handy.

  1. In the code editor window, scroll down to find the Parse method with a single string parameter and the comments that document it, starting on line 87, as shown in the following screenshot:
    A screenshot of a social media post

Description automatically generated

    Figure 1.10: The comments for the Parse method

In the comments, you will see that Microsoft has documented what exceptions might occur if you call this method, including ArgumentNullException, FormatException, and OverflowException. Now, we know that we need to wrap a call to this method in a try statement and which exceptions to catch.

Hopefully, you are getting impatient to learn what all this means!

Be patient for a little longer. You are almost at the end of this chapter, and in the next chapter, you will dive into the details of the C# language. But first, let's see where else you can look for help.

Looking for answers on Stack Overflow

Stack Overflow is the most popular third-party website for getting answers to difficult programming questions. It's so popular that search engines such as DuckDuckGo have a special way to write a query to search the site.

  1. Start your favorite web browser.
  2. Navigate to DuckDuckGo.com, enter the following query, and note the search results, which are also shown in the following screenshot:
    !so securestring

    Figure 1.11: Stack Overflow search results for securestring

Searching for answers using Google

You can search Google with advanced search options to increase the likelihood of finding what you need.

  1. Navigate to Google.
  2. Search for information about garbage collection using a simple Google query, and note that you will probably see a lot of ads for garbage collection services in your local area before you see the Wikipedia definition of garbage collection in computer science.
  3. Improve the search by restricting it to a useful site such as Stack Overflow, and by removing languages that we might not care about such as C++, Rust, and Python, or by adding C# and .NET explicitly, as shown in the following search query:
    garbage collection site:stackoverflow.com +C# -Java

Subscribing to the official .NET blog

To keep up to date with .NET, an excellent blog to subscribe to is the official .NET Blog written by the .NET engineering teams, and you can find it at the following link: https://devblogs.microsoft.com/dotnet/.

Scott Hanselman's videos

Scott Hanselman from Microsoft has an excellent YouTube channel about computer stuff they didn't teach you. I recommend it to everyone working with computers.

More Information: You can watch Scott's video series at the following link: http://computerstufftheydidnteachyou.com/


Practicing and exploring

Let's now test your knowledge and understanding by trying to answer some questions, getting some hands-on practice, and exploring with deeper research into the topics covered throughout this chapter.

Exercise 1.1 – Test your knowledge

Try to answer the following questions, remembering that although most answers can be found in this chapter, some online research or code writing will be needed to answer others:

  1. Why can a programmer use different languages, for example, C# and F#, to write applications that run on .NET?
  2. What do you type at the prompt to create a console app?
  3. What do you type at the prompt to build and execute C# source code?
  4. What is the Visual Studio Code keyboard shortcut to view Terminal?
  5. Is Visual Studio 2019 better than Visual Studio Code?
  6. Is .NET Core better than .NET Framework?
  7. What is .NET Standard and why is it still important?
  8. What is the name of the entry point method of a .NET console application and how should it be declared?
  9. Where would you look for help about a C# keyword?
  10. Where would you look for solutions to common programming problems?

Exercise 1.2 – Practice C# anywhere

You don't need Visual Studio Code or even Visual Studio 2019 or Visual Studio 2019 for Mac to write C#. You can go to .NET Fiddle – https://dotnetfiddle.net/ – and start coding online.

Exercise 1.3 – Explore topics

You can use the following links to read more details about the topics we've covered in this chapter:



In this chapter, we:

  • Set up your development environment.
  • Discussed the differences between .NET 5, .NET Core, .NET Framework, Xamarin, and .NET Standard.
  • Used Visual Studio Code and .NET SDK to create a simple console application.
  • Learned how to download the solution code for this book from a GitHub repository.
  • And most importantly, we learned how to find help.

In the next chapter, you will learn to speak C#.

About the Author

  • Mark J. Price

    Mark J. Price is a Microsoft Specialist: Programming in C# and Architecting Microsoft Azure Solutions, with over 20 years’ experience. Since 1993, he has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them. Between 2001 and 2003, Mark was employed to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught "train-the-trainer" classes to get other MCTs up-to-speed on C# and .NET. Currently, Mark creates and delivers training courses for Episerver's Digital Experience Platform. Mark holds a Computer Science BSc. Hons. Degree and a Postgraduate Certificate in Education.

    Browse publications by this author

Latest Reviews

(13 reviews total)
I have bought previous version of this book and it is an excellent book.
Good information, easy to read.
i am reading it now and the author is awesome it write every details and added some references i am willing to finish it soon and I hope he wrote another one when .Net 6 is released

Recommended For You

Book Title
Access this book, plus 7,500 other titles for FREE
Access now