Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
C# 13 and .NET 9 – Modern Cross-Platform Development Fundamentals
C# 13 and .NET 9 – Modern Cross-Platform Development Fundamentals

C# 13 and .NET 9 – Modern Cross-Platform Development Fundamentals: Start building websites and services with ASP.NET Core 9, Blazor, and EF Core 9 , Ninth Edition

Arrow left icon
Profile Icon Mark J. Price
Arrow right icon
$27.98 $39.99
eBook Nov 2024 828 pages 9th Edition
eBook
$27.98 $39.99
Paperback
$31.99 $49.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Mark J. Price
Arrow right icon
$27.98 $39.99
eBook Nov 2024 828 pages 9th Edition
eBook
$27.98 $39.99
Paperback
$31.99 $49.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$27.98 $39.99
Paperback
$31.99 $49.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

C# 13 and .NET 9 – Modern Cross-Platform Development Fundamentals

Hello, C#! Welcome, .NET!

In this first chapter, the first goal is setting up your development environment to use Visual Studio 2022, Visual Studio Code, or JetBrains Rider.

Throughout this book, I will use the names Visual Studio, VS Code, and Rider to refer to these three code editors, respectively.

The other goals are understanding the similarities and differences between modern .NET, .NET Core, .NET Framework, Mono, Xamarin, and .NET Standard; creating the simplest application possible with C# 13 and .NET 9, using various code editors; and then discovering good places to look for help.

My style of writing ensures that you can get started from my book and then switch to online documentation and other online resources, like videos, blogs, and forums, which are the main ways that developers like to learn, as shown at the following link: https://survey.stackoverflow.co/2024/developer-profile#learning-to-code.

This chapter covers the following topics:

  • Introducing this book and its contents
  • Setting up your development environment
  • Understanding .NET
  • Building console apps using Visual Studio
  • Building console apps using VS Code
  • Making good use of the GitHub repository for this book
  • Looking for help

Introducing this book and its contents

Let’s get started by introducing you to the code solutions, structure, and content of this book.

Getting code solutions for this book

The GitHub repository for this book has solutions that use full application projects for all code tasks and exercises, found at the following link:

https://github.com/markjprice/cs13net9

After navigating to the GitHub repository in your web browser, press the . (dot) key on your keyboard, or manually change .com to .dev in the link to convert the repository into a live code editor based on VS Code, called GitHub Codespaces, as shown in Figure 1.1:

Figure 1.1: GitHub Codespaces live-editing the book’s GitHub repository

Warning! When you access a repository using GitHub Codespaces, its GitHub Repositories extension will attempt to download the repository’s index. By default, the maximum size can be up to 50MB but the repository exceeds this limit, so you will see the following warning message: Repository exceeds download size limit! Continuing with partial text services. You can ignore this message because you are not using the full features.

We provide you with a PDF file that has color images of the screenshots and diagrams used in this book. You can download this file from https://packt.link/gbp/9781837635870.

VS Code in a web browser is great to run alongside your chosen local code editor as you work through the book’s coding tasks. You can compare your code to the solution code and easily copy and paste parts if needed.

You do not need to use or know anything about Git to get the solution code of this book. You can download a ZIP file containing all the code solutions by using the following direct link and then extract the ZIP file into your local filesystem: https://github.com/markjprice/cs13net9/archive/refs/heads/main.zip.

.NET terms used in this book

Throughout this book, I use the term modern .NET to refer to .NET 9 and its predecessors, like .NET 6, that derive from .NET Core. I use the term legacy .NET to refer to .NET Framework, Mono, Xamarin, and .NET Standard.

Modern .NET is a unification of those legacy platforms and standards.

The structure and style of this book

After this first chapter, the book will be divided into three parts: language, libraries, and web development.

First, we will cover the grammar and vocabulary of the C# language; second, we will cover the types available in the .NET libraries for building app features; and third, we will cover the fundamentals of cross-platform websites, services, and browser apps that 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 and 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.

If you have a complaint about this book, then please contact me before writing a negative review on Amazon. Authors cannot respond to Amazon reviews, so I cannot contact you to resolve the problem and help you or listen to your feedback and try to do better in the next edition. Please ask a question on the Discord channel for this book at https://packt.link/csharp13dotnet9, email me at markjprice@gmail.com, or raise an issue in the GitHub repository for the book at the following link: https://github.com/markjprice/cs13net9/issues.

Topics covered by this book

The following topics are covered in this book:

  • Language fundamentals: Fundamental features of the C# language, from declaring variables to writing functions and object-oriented programming.
  • Library fundamentals: Fundamental features of the .NET base class library, as well as some important optional packages for common tasks like database access.
  • Modern web development fundamentals: Modern features of the ASP.NET Core framework for server-side and client-side website and web service development. This includes Blazor and Minimal APIs and excludes controller-based features like MVC and Web API, or legacy features like Razor Pages.

This book, C# 13 and .NET 9 – Modern Cross-Platform Development Fundamentals, is best read linearly, chapter by chapter, because it builds up fundamental skills and knowledge.

Topics covered by Apps and Services with .NET 8

The following topics are available in a companion book, Apps and Services with .NET 8:

  • Data: SQL Server and Azure Cosmos DB.
  • Specialized libraries: Dates, times, time zones, and internationalization; common third-party libraries for image handling, logging, mapping, and generating PDFs; multitasking and concurrency; and many more.
  • Services: Caching, queuing, background services, gRPC, GraphQL, Azure Functions, SignalR, and Minimal APIs.
  • User interfaces: ASP.NET Core, Blazor, and .NET MAUI.

This book can be read more like a cookbook, so if you are especially interested in building gRPC services, then you can read that chapter without the preceding chapters about minimal API services.

Topics covered by Tools and Skills for .NET 8

The following topics are available in a companion book, Tools and Skills for .NET 8:

  • Debugging and memory analysis.
  • All the important types of testing, from unit and integration to performance and web UI testing.
  • Docker and .NET Aspire for local distributed development and testing.
  • Design patterns and solution architecture.
  • Preparing for an interview to get the .NET developer career that you want.

My books for .NET 8 are equally applicable to .NET 9. You can make your projects target .NET 9 and all the code examples will work. You should not need to wait for packages to upgrade to also target .NET 9, due to backward compatibility.

Finding all my books

To see a list of all the books I have published with Packt, you can use the following link:

https://subscription.packtpub.com/search?query=mark+j.+price

A similar list is available on Amazon:

https://www.amazon.com/Mark-J-Price/e/B071DW3QGN/

You can search other book-selling sites for my books too.

Setting up your development environment

Before you start programming, you’ll need a code editor for C#, either from Microsoft or a third party.

Microsoft has a family of code editors and Integrated Development Environments (IDEs), which include:

  • Visual Studio for Windows
  • VS Code for Windows, Mac, or Linux
  • VS Code for the Web or GitHub Codespaces

Third parties have created their own C# code editors; for example, JetBrains has the cross-platform Rider, which is available for Windows, Mac, or Linux and since October 2024 is free for non-commercial use. Rider is popular with more experienced .NET developers.

Warning! Although JetBrains is a fantastic company with great products, both Rider and the ReSharper extension for Visual Studio are software, and all software has bugs and quirky behavior. For example, they might show errors like Cannot resolve symbol in your Razor Pages, Razor views, and Blazor components. Yet you can build and run those files because there is no actual problem. If you have installed the Unity Support plugin, then it will complain about boxing operations (which are a genuine problem for Unity game developers) but in projects that are not Unity; hence, the warning is not applicable.

Most readers use Visual Studio, which is a large and complex tool that can do many things. But Visual Studio likes to provide its own mechanism to do as much as possible, and a .NET developer who uses it could easily think that Visual Studio is the only way to complete a .NET-related task, like modifying project configuration or editing a code file.

Always try to remember that Visual Studio and all the other code editors are just tools that do work for you that you could do manually. They just show you a view above what is really happening in the files you’re working on, like the project file and all the C# code files.

You could just use a plain text editor to manually edit the project and code files. Ultimately, you use the dotnet command-line interface to compile– aka build– the project files into a runnable assembly packaged as either a .dll or .exe file, as shown in Figure 1.2:

Figure 1.2: All code editors ultimately just change underlying files

Choosing the appropriate tool and application type for learning

What is the best tool and application type for learning C# and .NET?

When learning, the best tool is one that helps you write code and configuration but does not hide what is really happening. IDEs provide graphical user interfaces that are friendly to use, but what are they doing for you underneath? A more basic code editor that is closer to the action while providing help to write your code can be better while you are learning.

Having said that, you could make the argument that the best tool is the one you are already familiar with or that you or your team will use as your daily development tool. For that reason, I want you to be free to choose any C# code editor or IDE to complete the coding tasks in this book, including VS Code, Visual Studio, and even Rider.

In this book, I give detailed step-by-step instructions in this chapter on how to create multiple projects in both Visual Studio and VS Code. There are also links to online instructions for other code editors, as shown at the following link: https://github.com/markjprice/cs13net9/blob/main/docs/code-editors/README.md.

In subsequent chapters, I will only give the names of projects along with general instructions, so you can use whichever tool you prefer.

The best application type for learning the C# language constructs and many of the .NET libraries is one that does not distract with unnecessary application code. For example, there is no need to create an entire Windows desktop application or a website just to learn how to write a switch statement.

For that reason, I believe the best method for learning the C# and .NET topics in Chapters 1 to 11 is to build console apps. Then, in Chapters 12 to 15, which are about web development, you will build websites and services using the modern parts of ASP.NET Core, including Blazor and Minimal APIs.

VS Code for cross-platform development

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

VS 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#. The most important extension for C# and .NET developers is the C# Dev Kit that was released in preview in June 2023, as it turns VS Code from a general-purpose code editor into a tool optimized for C# and .NET developers.

More Information: You can read about the C# Dev Kit extension in the official announcement at the following link: https://devblogs.microsoft.com/visualstudio/announcing-csharp-dev-kit-for-visual-studio-code/.

Being cross-platform and lightweight, VS Code and its extensions can be installed on all platforms that your apps will be deployed to for quick bug fixes and so on. Choosing VS Code means a developer can use a cross-platform code editor to develop cross-platform apps. VS Code is supported on ARM processors so that you can develop on Apple Silicon computers and Raspberry Pi computers.

VS Code has strong support for web development, although it currently has weak support for mobile and desktop development.

VS Code is by far the most popular code editor or IDE, with over 73% of professional developers selecting it in a Stack Overflow survey, which you can read at the following link: https://survey.stackoverflow.co/2024/.

GitHub Codespaces for development in the cloud

GitHub Codespaces is a fully configured development environment, based on VS 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.

But note that for your GitHub Codespaces experience to be fully functional and practically useful, it does have a license cost.

More Information: You can learn more about GitHub Codespaces at the following link: https://github.com/features/codespaces.

Visual Studio for general development

Visual Studio can create most types of applications, including console apps, websites, web services, and desktop apps. Although you can use Visual Studio to write a cross-platform mobile app, you still need macOS and Xcode to compile it.

Visual Studio only runs on Windows 10 version 1909 or later, Home, Professional, Education, or Enterprise; or on Windows 11 version 21H2 or later, Home, Pro, Pro Education, Pro for Workstations, Enterprise, or Education. Windows Server 2016 and later are also supported. 32-bit operating systems and Windows S mode are not supported.

Warning! Visual Studio for Mac does not officially support .NET 8 or later, and it reached its end of life in August 2024. If you have been using Visual Studio for Mac, then you should switch to VS Code for Mac, Rider for Mac, or use Visual Studio for Windows in a virtual machine on your local computer or in the cloud, using a technology like Microsoft Dev Box. The retirement announcement can be read here: https://devblogs.microsoft.com/visualstudio/visual-studio-for-mac-retirement-announcement/.

What I used

To write and test the code for this book, I used the following hardware and software:

  • Windows 11 on a Surface Laptop 7 Copilot+ PC with Visual Studio, VS Code, and Rider.
  • macOS on an Apple Silicon Mac mini (M1) desktop with VS Code and Rider.

I hope that you have access to a variety of hardware and software too, as seeing the differences in platforms deepens your understanding of development challenges, although any one of the above combinations is enough to learn the fundamentals of C# and .NET and how to build practical apps and websites.

Deploying cross-platform

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

.NET 9 supports the following platforms for deployment:

  • Windows: Windows 10 version 1607 or later, Windows 11 version 22000 or later, Windows Server 2012 R2 SP1 or later, and Nano Server version 2019 or 2022.
  • Mac: macOS Catalina version 10.15 or later and in the Rosetta 2 x64 emulator.
  • Linux: Alpine Linux 3.19 or 3.20, CentOS Stream 9, Debian 12, Fedora 40, openSUSE 15.5 or 15.6, RHEL 8 or 9, SUSE Enterprise Linux 15.5 or 15.6, and Ubuntu 20.04, 22.04, or 24.04.
  • Android: API 21 or later is the minimum SDK target. Versions 12, 12.1, 13, and 14.
  • iOS and iPadOS: 15, 16, or 17. iOS 12.2 is used as the minimum SDK target.
  • Mac Catalyst: 12, 13, or 14.

Warning! .NET support for Windows 7 and 8.1 ended in January 2023: https://github.com/dotnet/core/issues/7556.

Windows Arm64 support in .NET 5 and later means you can develop on, and deploy to, Windows Arm devices like Microsoft’s Windows Dev Kit 2023 (formerly known as Project Volterra) and Surface Pro 11 and Surface Laptop 7.

You can review the latest supported operating systems and versions at the following link: https://github.com/dotnet/core/blob/main/release-notes/9.0/supported-os.md.

All versions of .NET that are supported can be automatically patched via Microsoft Update on Windows.

Downloading and installing Visual Studio

Many professional .NET developers use Visual Studio in their day-to-day development work. Even if you choose to use VS Code to complete the coding tasks in this book, you might want to familiarize yourself with Visual Studio too. It is not until you have written a decent amount of code with a tool that you can really judge if it fits your needs.

If you do not have a Windows computer, then you can skip this section and continue to the next section, where you will download and install VS Code on macOS or Linux.

Since October 2014, Microsoft has made a professional-quality edition of Visual Studio available to students, open-source contributors, and individuals for free. It is called Community Edition. Any of the editions are suitable for this book. If you have not already installed it, let’s do so now:

  1. Download the latest version of Visual Studio from the following link: https://visualstudio.microsoft.com/downloads/.

Visual Studio vNext: At the time of writing, Visual Studio is version 17.12 and branded as Visual Studio 2022. I expect the next major version of Visual Studio to be version 18.0 and be branded as Visual Studio 2025. It is likely to be released in the first half of 2025, after this book is published. Visual Studio 2025 will have mostly the same features as the 2022 edition, although the user interface might move things around a bit.

  1. Run the installer to start the installation.
  2. On the Workloads tab, select the following:
    • ASP.NET and web development.
    • .NET desktop development (because this includes console apps).
    • Desktop development with C++ with all default components (because this enables you to publish console apps and web services that start faster and have smaller memory footprints).
  3. Click Install and wait for the installer to acquire the selected software, and then install it.
  4. When the installation is complete, click Launch.
  5. The first time that you run Visual Studio, you will be prompted to sign in. If you have a Microsoft account, you can use that account. If you don’t, then register for a new one at the following link: https://signup.live.com/.
  6. The first time that you run Visual Studio, you will be prompted to configure your environment. For Development Settings, choose Visual C#. For the color theme, I chose Blue, but you can choose whatever tickles your fancy.
  7. If you want to customize your keyboard shortcuts, navigate to Tools | Options…, and then select the Keyboard section.

Keyboard shortcuts for Visual Studio

In this book, I will avoid showing keyboard shortcuts, since they are often customized. Where they are consistent across code editors and commonly used, I will try to show them.

If you want to identify and customize your keyboard shortcuts, then you can, as shown at the following link: https://learn.microsoft.com/en-us/visualstudio/ide/identifying-and-customizing-keyboard-shortcuts-in-visual-studio.

Downloading and installing VS Code

VS 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 the Insiders edition, which is a daily build of the next version.

Even if you plan to only use Visual Studio for development, I recommend that you download and install VS Code and try the coding tasks in this chapter using it, and then decide if you want to stick with just using Visual Studio for the rest of the book.

Let’s now download and install VS Code, the .NET SDK, and the C# Dev Kit extension:

  1. Download and install either the Stable build or the Insiders edition of VS Code from the following link: https://code.visualstudio.com/.

More Information: If you need more help installing VS Code, you can read the official setup guide at the following link: https://code.visualstudio.com/docs/setup/setup-overview.

  1. Download and install the .NET SDK for version 9.0 and version 8.0 from the following link: https://www.microsoft.com/net/download.

In real life, you are extremely unlikely to only have one .NET SDK version installed on your computer. To learn how to control which .NET SDK version is used to build a project, we need multiple versions installed. .NET 8 and .NET 9 are the only supported versions at the time of publishing in November 2024. You can safely install multiple SDKs side by side. The most recent SDK will be used to build your projects.

  1. To install the C# Dev Kit extension with a user interface, you must first launch the VS Code application.
  2. In VS Code, click the Extensions icon or navigate to View | Extensions.
  3. C# Dev Kit 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.

C# Dev Kit has a dependency on the C# extension version 2.0 or later, so you do not have to install the C# extension separately. Note that C# extension version 2.0 or later no longer uses OmniSharp, since it has a new Language Server Protocol (LSP) host. C# Dev Kit also has dependencies on the .NET Install Tool for Extension Authors and IntelliCode for C# Dev Kit extensions, so they will be installed too.

  1. Click Install and wait for the supporting packages to download and install.

Good Practice: Be sure to read the license agreement for C# Dev Kit. It has a more restrictive license than the C# extension: https://aka.ms/vs/csdevkit/license.

Installing other extensions

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

Extension name and identifier

Description

C# Dev Kit

ms-dotnettools.csdevkit

Official C# extension from Microsoft. Helps you manage your code with a solution explorer and test your code with integrated unit test discovery and execution, elevating your C# development experience wherever you like to develop (Windows, macOS, Linux, and even in a codespace).

C#

ms-dotnettools.csharp

Provides rich language support for C# and is shipped along with C# Dev Kit. Powered by a Language Server Protocol (LSP) server, this extension integrates with open source components like Roslyn and Razor to provide rich type information and a faster, more reliable C# experience.

IntelliCode for C# Dev Kit

ms-dotnettools.vscodeintellicode-csharp

Provides AI-assisted development features for Python, TypeScript/JavaScript, C#, and Java developers.

MSBuild project tools

tintoy.msbuild-project-tools

Provides IntelliSense for MSBuild project files, including autocomplete for <PackageReference> elements.

Markdown All in One

yzhang.markdown-all-in-one

All you need for Markdown (keyboard shortcuts, table of contents, auto preview, and more).

Polyglot Notebooks

ms-dotnettools.dotnet-interactive-vscode

This extension adds support for using .NET and other languages in a notebook. It has a dependency on the Jupyter extension (ms-toolsai.jupyter), which itself has dependencies.

ilspy-vscode

icsharpcode.ilspy-vscode

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

REST Client

humao.rest-client

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

Table 1.1: VS Code extensions for .NET development

You can install a VS Code extension at the command prompt or terminal, as shown in Table 1.2:

Command

Description

code --list-extensions

List installed extensions.

code --install-extension <extension-id>

Install the specified extension.

code --uninstall-extension <extension-id>

Uninstall the specified extension.

Table 1.2: Managing VS Code extensions at the command prompt

For example, to install the C# Dev Kit extension, enter the following at the command prompt:

code --install-extension ms-dotnettools.csdevkit

I have created PowerShell scripts to install and uninstall the VS Code extensions in the preceding table. You can find them at the following link: https://github.com/markjprice/cs13net9/tree/main/scripts/extension-scripts/. PowerShell scripts are cross-platform, as you can read about at the following link: https://learn.microsoft.com/en-us/powershell/scripting/overview.

Understanding VS Code versions

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

  • Version 1.93.0, August 2024 feature release
  • Version 1.93.1, August 2024 bug fix release

The version used in this book is 1.93.0, the August 2024 feature release, but the version of VS Code is less important than the version of the C# Dev Kit or C# extension that you install. I recommend C# Dev Kit v1.10.18 or later with C# extension v2.45.20 or 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 and keep updated to support the latest C# language features.

Keyboard shortcuts for VS Code

If you want to customize your keyboard shortcuts for VS Code, then you can, as shown at the following link: https://code.visualstudio.com/docs/getstarted/keybindings.

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

Understanding .NET

“Those who cannot remember the past are condemned to repeat it.”

– George Santayana

.NET, .NET Core, .NET Framework, .NET Standard, and Xamarin are related and overlapping platforms for developers used to build applications and services.

If you are not familiar with the history of .NET, then I will introduce you to each of these .NET concepts at the following link:

https://github.com/markjprice/cs13net9/blob/main/docs/ch01-dotnet-history.md

As time moves on, more and more readers already know the history of .NET, so it would be a waste of space in the book to continue to include it. But if you are new to it, then make sure you read all the extras that I provide online, like the preceding one.

Understanding .NET support

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

  • LTS releases are a good choice for applications that you do not intend to update frequently, although you must update the .NET runtime for your production code monthly. LTS releases are supported by Microsoft for 3 years after General Availability (GA), or 1 year after the next LTS release ships, whichever is longer.
  • STS 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. STS releases are supported by Microsoft for 18 months after GA, or 6 months after the next STS or LTS release ships, whichever is longer.
  • Preview releases are for public testing. These are a good choice for adventurous programmers who want to live on the bleeding edge, or programming book authors who need to have early access to new language features, libraries, and app and service platforms. Preview releases are not usually supported by Microsoft, but some preview or Release Candidate (RC) releases may be declared Go Live, meaning they are supported by Microsoft in production.

STS and LTS releases receive critical patches throughout their lifetime for security and reliability.

Good Practice: You must stay up to date with the latest patches to get support. For example, if a system is running on .NET runtime version 9.0.0 and then version 9.0.1 is released, you must install version 9.0.1 to get support. These updates are released on the second Tuesday of each month, aka Patch Tuesday.

To better understand your choices of STS and LTS releases, it is helpful to see them visualized, with 3-year-long black bars for LTS releases, and 1½-year-long gray bars for STS releases, as shown in Figure 1.3:

Figure 1.3: Support durations for recent and planned STS and LTS releases

During the lifetime of .NET 9, .NET 8 will still be supported and .NET 10 will be released. I have tried to be cognizant that you might choose to use .NET 8 or .NET 10 with this book; however, obviously, the book cannot cover new features of .NET 10, since I don’t know what they will be!

If you need LTS from Microsoft, then set your .NET projects to target .NET 8 today and then migrate to .NET 10 after it is released in November 2025. This is because .NET 9 is an STS release, and therefore, it will lose support in May 2026, before .NET 8 does in November 2026. As soon as .NET 10 is released, start upgrading your .NET 8 projects to it. You will have a year to do so before .NET 8 reaches its end of life.

Good Practice: Remember that with all releases, you must upgrade to bug-fix releases like .NET runtime 9.0.1 and .NET SDK 9.0.101, which are expected to release in December 2024, as updates are released every month.

At the time of publishing in November 2024, all versions of modern .NET have reached their EOL, except those shown in the following list, which are ordered by their EOL dates:

  • .NET 9 will reach EOL in May 2026.
  • .NET 8 will reach EOL in November 2026.
  • .NET 10 will be available from November 2025 and it will reach EOL in November 2028.

You can check which .NET versions are currently supported and when they will reach EOL at the following link: https://github.com/dotnet/core/blob/main/releases.md.

Understanding end of life (EOL)

End of support or end of life (EOL) means the date after which bug fixes, security updates, or technical assistance are no longer available from Microsoft.

For example, now that .NET 6 has reached end of support on November 12, 2024, you can expect the following:

  • Projects that use .NET 6 will continue to run.
  • No new security updates will be issued for .NET 6 and therefore continuing to use an unsupported version will increasingly expose you to security vulnerabilities.
  • You might not be able to access technical support for any .NET 6 applications that you continue to use.
  • You will get NETSDK1138 build warnings when targeting .NET 6 from a later SDK like the .NET 9 SDK.
  • You will get warnings in Visual Studio when targeting .NET 6.

Understanding .NET support phases

The lifetime of a version of .NET passes through several phases, during which they have varying levels of support, as described in the following list:

  • Preview: These are not supported at all. .NET 9 Preview 1 to Preview 7 were in this support phase from February 2024 to August 2024.
  • Go Live: These are supported until GA, and then they become immediately unsupported. You must upgrade to the final release version as soon as it is available. .NET 9 Release Candidate 1 and Release Candidate 2 were in this support phase in September and October 2024, respectively.
  • Active: .NET 9 will be in this support phase from November 2024 to November 2025.
  • Maintenance: Supported only with security fixes for the last 6 months of its lifetime. .NET 9 will be in this support phase from November 2025 to May 2026.
  • EOL: Not supported. .NET 9 will reach its EOL in May 2026.

Understanding .NET runtime and .NET SDK versions

If you have not built a standalone app, then the .NET runtime is the minimum you need to install so that an operating system can run a .NET application. The .NET SDK includes the .NET runtime, as well as the compilers and other tools needed to build .NET code and apps.

.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 they are matched with. The third number follows a convention that indicates the minor and patch versions of the SDK. The third number starts at 100 for the initial version (equivalent to 0.0 for the minor and patch numbers). The first digit increments with minor increments, and the other two digits increment with patch increments.

You can see an example of this in Table 1.3:

Change

Runtime

SDK

Initial release

9.0.0

9.0.100

SDK bug fix

9.0.0

9.0.101

Runtime and SDK bug fix

9.0.1

9.0.102

SDK new feature

9.0.1

9.0.200

Table 1.3: Examples of changes and versions for a .NET runtime and SDK

Listing and removing versions of .NET

.NET runtime updates are compatible with a major version such as 9.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
dotnet --info

Good Practice: To make it easier to enter commands at the command prompt or terminal, the following link lists all commands throughout the book that can be easily copied and pasted: https://github.com/markjprice/cs13net9/blob/main/docs/command-lines.md.

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

On Linux, there is no single mechanism, but you can learn more at the following link:

https://learn.microsoft.com/en-us/dotnet/core/install/remove-runtime-sdk-versions?pivots=os-linux

You could use a third-party tool like Dots, the friendly .NET SDK manager, found at the following link: https://johnnys.news/2023/01/Dots-a-dotnet-SDK-manager. At the time of writing, you must build the app from source on its GitHub repository, so I only recommend that for advanced developers.

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, the newer name for the Common Language Runtime (CLR) in modern .NET. The legacy .NET Framework has a CLR that is Windows-only, and modern .NET has one for each OS, like Windows, macOS, and Linux. These days, they are all commonly referred to as CLRs.

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 two-step compilation process is that Microsoft can create CLRs for Linux and macOS, as well as for Windows. The same IL code runs everywhere because of the second compilation step, 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. You will learn more about this in Chapter 7, Packaging and Distributing .NET Types, in an online section found at the following link: https://github.com/markjprice/cs13net9/blob/main/docs/ch07-decompiling.md.

So, the compilation process typically involves translating source code into IL, which is then compiled into machine code at runtime by the CLR using JIT compilation. Ahead-of-Time (AOT) compilation is an alternative to this approach, and you will learn about it in Chapter 7, Packaging and Distributing .NET Types.

Comparing .NET technologies

We can summarize and compare the current .NET technologies, as shown in Table 1.4:

Technology

Description

Host operating systems

Modern .NET

A modern feature set, with full C# 8 to C# 13 language support. It can be used to port existing apps or create new desktop, mobile, and web apps and services.

Windows, macOS, Linux, Android, iOS, tvOS, and Tizen

.NET Framework

A legacy feature set with limited C# 8 support and no C# 9 or later support. It should be used to maintain existing applications only.

Windows only

Xamarin

Mobile and desktop apps only.

Android, iOS, and macOS

Table 1.4: Comparison of .NET technologies

Visual Studio, Rider, and even VS Code (with the C# Dev Kit extension installed) all have a concept called a solution that allows you to open and manage multiple projects simultaneously. We will use a solution to manage the two projects that you will create in this chapter.

Building console apps using Visual Studio

The goal of this section is to showcase how to build a console app using Visual Studio.

If you do not have a Windows computer or want to use VS Code, then you can skip this section, since the code will be the same; just the tooling experience is different. However, I recommend that you review this section because it does explain some of the code and how top-level programs work, and that information applies to all code editors.

This section is also available in the GitHub repository (so it can be updated after publishing if needed) at the following link:

https://github.com/markjprice/cs13net9/blob/main/docs/code-editors/vs.md

If you want to see similar instructions for using Rider, they are available in the GitHub repository at the following link:

https://github.com/markjprice/cs13net9/blob/main/docs/code-editors/rider.md

Writing code using Visual Studio

Let’s get started writing code:

  1. Start Visual Studio.
  2. In the Create a new project dialog, select the C# language to filter the project templates, enter console in the Search for templates box, and then select Console App.

Make sure that you have chosen the cross-platform project template, not the one for .NET Framework, which is Windows-only, and the C# project template rather than another language, such as Visual Basic or TypeScript.

  1. Click Next.
  2. In the Configure your new project dialog, enter HelloCS for the project name, C:\cs13net9 for the location, and Chapter01 for the solution name.

Screenshots of Visual Studio when creating new projects can be found in the GitHub repository at the following link: https://github.com/markjprice/cs13net9/blob/main/docs/ch01-project-options.md.

  1. Click Next.
  2. In the Additional information dialog, in the Framework drop-down list, note that your .NET SDK choices indicate if that version is Standard Term Support, Long Term Support, Preview, or Out of support, and then select .NET 9.0 (Standard Term Support).

You can install as many .NET SDK versions as you like. If you are missing a .NET SDK version, then you can install it from the following link: https://dotnet.microsoft.com/en-us/download/dotnet.

  1. Leave the checkbox labeled Do not use top-level statements clear. (Later in this chapter, you will create a console app that selects this option, so you will see the difference.)
  2. Leave the checkbox labeled Enable native AOT publish clear. You will learn what this option does in Chapter 7, Packaging and Distributing .NET Types.
  3. Click Create.
  4. If you cannot see Solution Explorer, then navigate to View | Solution Explorer.
  5. If code is not shown, then in Solution Explorer, double-click the file named Program.cs to open it, and note that Solution Explorer shows the HelloCS project, as shown in Figure 1.4:

Figure 1.4: Editing Program.cs in Visual Studio

  1. In Program.cs, note that the code consists of only a comment and a single statement, as shown in the following code:
    // See https://aka.ms/new-console-template for more information
    Console.WriteLine("Hello, World!");
    

    This template uses the top-level program feature introduced in C# 9, which I will explain later in this chapter. As the comment in the code says, you can read more about this template at the following link: https://aka.ms/new-console-template.

  1. In Program.cs, modify line 2 so that the text that is being written to the console says Hello, C#!.

    All code examples and commands that you must review or type are shown in plain text, so you will never have to read code or commands from a screenshot, like in Figure 1.4, which might be too small or too faint in print.

Compiling and running code using Visual Studio

The next task is to compile and run the code:

  1. In Visual Studio, navigate to Debug | Start Without Debugging.

Good Practice: When you start a project in Visual Studio, you can choose whether to attach a debugger or not. If you do not need to debug, then it is better not to attach one because attaching a debugger requires more resources and slows everything down. Attaching a debugger also limits you to only starting one project. If you want to run more than one project, each with a debugger attached, then you must start multiple instances of Visual Studio. In the toolbar, click the green outline triangle button (to the right of HelloCS in the top bar shown in Figure 1.5) to start without debugging, instead of the green solid triangle button (to the left of HelloCS in the top bar shown in Figure 1.5), unless you need to debug.

  1. The output in the console window will show the result of running your application, as shown in Figure 1.5:

Figure 1.5: Running the console app on Windows

  1. Press any key to close the console app window and return to Visual Studio.
  2. Optionally, close the Properties pane to make more vertical space for Solution Explorer.
  3. Double-click the HelloCS project, and note that the HelloCS.csproj project file shows that this project has its target framework set to net9.0, as shown in Figure 1.6.
  4. In the Solution Explorer toolbar, toggle on the Show All Files button, and note that the compiler-generated bin and obj folders are visible, as shown in Figure 1.6:

Figure 1.6: Showing the compiler-generated folders and files

Understanding the compiler-generated folders and files

Two compiler-generated folders were created, named obj and bin, as described in the following list:

  • The obj folder contains one compiled object file for each source code file. These objects haven’t been linked together into a final executable yet.
  • The bin folder contains the binary executable for the application or class library. We will look at this in more detail in Chapter 7, Packaging and Distributing .NET Types.

You do not need to look inside these folders or understand their files yet (but feel free to browse around if you are curious).

Just be aware that the compiler needs to create temporary folders and files to do its work. You could delete these folders and their files, and they will be automatically recreated the next time you “build” or run the project. Developers often delete these temporary folders and files to “clean” a project. Visual Studio even has a command on the Build menu named Clean Solution that deletes some of these temporary files for you. The equivalent command with the CLI is dotnet clean.

Understanding top-level programs

If you have seen older .NET projects before, then you might have expected more code, even just to output a simple message. This project has minimal statements because some of the required code is written for you by the compiler when you target .NET 6 or later.

If you had created the project with .NET SDK 5 or earlier, or if you had selected the checkbox labeled Do not use top-level statements, then the Program.cs file would have more statements, as shown in the following code:

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

During compilation with .NET SDK 6 or later, all the boilerplate code to define the Program class and its Main method is generated and wrapped around the statements you write.

This uses a feature introduced in .NET 5 called top-level programs, but it was not until .NET 6 that Microsoft updated the project template for console apps to use top-level statements by default. Then, in .NET 7 and later, Microsoft added options to use the older style if you prefer:

  • If you are using Visual Studio, select the checkbox labeled Do not use top-level statements.
  • If you are using the dotnet CLI at the command prompt, add a switch:
    dotnet new console --use-program-main
    

Warning! One functional difference is that the auto-generated code does not define a namespace, so the Program class is implicitly defined in an empty namespace with no name, instead of a namespace that matches the name of the project.

Requirements for top-level programs

Key points to remember about top-level programs include the following:

  • There can be only one file like the file you use for top-level program code in a project.
  • Any using statements must be at the top of the file.
  • If you declare any classes or other types, they must be at the bottom of the file.
  • Although you should name the entry-point method Main if you explicitly define it, the method is named <Main>$ when created by the compiler.

Implicitly imported namespaces

The using System; statement at the top of the file imports the System namespace. This enables the Console.WriteLine statement to work. But why do we not have to import it in our project?

The trick is that we still need to import the System namespace, but it is now done for us using a combination of features introduced in C# 10 and .NET 6. Let’s see how:

  1. In Solution Explorer, expand the obj, Debug, and net9.0 folders, and open the file named HelloCS.GlobalUsings.g.cs.
  2. Note that this file is automatically created by the compiler for projects that target .NET 6 or later and uses a feature introduced in C# 10, called global namespace imports, which imports some commonly used namespaces like System for use in all code files, as shown in the following code:
    // <autogenerated />
    global using global::System;
    global using global::System.Collections.Generic;
    global using global::System.IO;
    global using global::System.Linq;
    global using global::System.Net.Http;
    global using global::System.Threading;
    global using global::System.Threading.Tasks;
    
  3. In Solution Explorer, click the Show All Files button to hide the bin and obj folders.

I will explain more about the implicit imports feature in the next chapter. For now, just note that a significant change that happened between .NET 5 and .NET 6 is that many of the project templates, like the one for console apps, use new SDK and language features to hide what is really happening.

Revealing the hidden code by throwing an exception

Now let’s discover how the hidden code has been written:

  1. In Program.cs, after the statement that outputs the message, add a statement to throw a new exception, as shown in the following code:
    throw new Exception();
    
  2. In Visual Studio, navigate to Debug | Start Without Debugging. (Do not start the project with debugging, or the exception will be caught by the debugger!)
  3. The output in the console window will show the result of running your application, including that a hidden Program class was defined by the compiler, with a method named <Main>$ that has a parameter named args to pass in arguments, as shown in Figure 1.7 and the following output:
    Hello, C#!
    Unhandled exception. System.Exception: Exception of type 'System.Exception' was thrown.
       at Program.<Main>$(String[] args) in C:\cs13net9\Chapter01\HelloCS\Program.cs:line 3
    

Figure 1.7: Throwing an exception to reveal the hidden Program.<Main>$ method

  1. Press any key to close the console app window and return to Visual Studio.

Revealing the namespace for the Program class

Now, let’s discover what namespace the Program class has been defined within:

  1. In Program.cs, before the statement that throws an exception, add statements to get the name of the namespace of the Program class, and then write it to the console, as shown in the following code:
    string name = typeof(Program).Namespace ?? "<null>";
    Console.WriteLine($"Namespace: {name}");
    

?? is the null-coalescing operator. The first statement means, “If the namespace of Program is null, then return <null>; otherwise, return the name.” You will see more explanations of these keywords and operators throughout the book. For now, just enter the code and run it to see what it does.

Good Practice: Code editors have a feature named code snippets. These allow you to insert pieces of code that you commonly use, by typing a shortcut and pressing Tab twice. For example, in Visual Studio, to enter Console.WriteLine() and leave the cursor in the middle of the parentheses ready for you to type what you want to output, type cw, and then press Tab, Tab. Read the documentation for your code editor to learn how to insert code snippets using shortcuts.

  1. In Visual Studio, navigate to Debug | Start Without Debugging.
  2. The output in the console window will show the result of running your application, including that the hidden Program class was defined without a namespace, as shown in the following output:
    Namespace: <null>
    
  3. Press any key to close the console app window and return to Visual Studio.

Adding a second project using Visual Studio

Let’s add a second project to our solution to explore how to work with multiple projects:

  1. In Visual Studio, navigate to File | Add | New Project….

    Warning! The above step adds a new project to the existing solution. Do NOT navigate to File | New | Project…, which instead is meant to be used to create a new project and solution (although the dialog box has a dropdown to choose to add to an existing solution too).

  1. In the Add a new project dialog, in Recent project templates, select Console App [C#], and then click Next.
  2. In the Configure your new project dialog, for Project name, enter AboutMyEnvironment, leave the location as C:\cs13net9\Chapter01, and then click Next.
  3. In the Additional information dialog, select .NET 9.0 (Standard Term Support) and select the Do not use top-level statements checkbox.

Warning! Make sure you have selected the Do not use top-level statements checkbox so that we get to see the older style of Program.cs.

  1. Click Create.
  2. In the AboutMyEnvironment project, in Program.cs, note the statements to define a namespace that matches the project name, an internal class named Program, and a static method named Main with a parameter named args that returns nothing (void), as shown in the following code:
    namespace AboutMyEnvironment
    {
      internal class Program
      {
        static void Main(string[] args)
        {
          Console.WriteLine("Hello, World!");
        }
      }
    }
    
  3. In Program.cs, in the Main method, replace the existing Console.WriteLine statement with statements to output the current directory, the version of the operating system, and the namespace of the Program class, as shown in the following code:
    Console.WriteLine(Environment.CurrentDirectory);
    Console.WriteLine(Environment.OSVersion.VersionString);
    Console.WriteLine("Namespace: {0}",
      typeof(Program).Namespace ?? "<null>");
    
  4. In Solution Explorer, right-click the Chapter01 solution, and then select Configure Startup Projects….
  5. In the Solution ‘Chapter01’ Property Pages dialog box, set Startup Project to Current selection, and then click OK.
  6. In Solution Explorer, click the AboutMyEnvironment project (or any file or folder within it), and note that Visual Studio indicates that AboutMyEnvironment is now the startup project by making the project name bold.

Good Practice: I recommend this way of setting the startup project because it then makes it very easy to switch startup projects by simply clicking a project (or any file in a project) to make it the startup project. Although you can right-click a project and set it as a startup project, if you then want to run a different project, you must manually change it again. Simply clicking anywhere in the project is easier. In most chapters, you will only need to run one project at a time. In Chapter 15, Building and Consuming Web Services, I will show you how to configure multiple startup projects.

  1. Navigate to Debug | Start Without Debugging to run the AboutMyEnvironment project, and note the result, as shown in the following output and Figure 1.8:
    C:\cs13net9\Chapter01\AboutMyEnvironment\bin\Debug\net9.0
    Microsoft Windows NT 10.0.26100.0
    Namespace: AboutMyEnvironment
    

Figure 1.8: Running a console app in a Visual Studio solution with two projects

Windows 11 is just branding. Its official name is Windows NT, and its major version number is still 10! But its patch version is 22000 or higher.

  1. Press any key to close the console app window and return to Visual Studio.

    When Visual Studio runs a console app, it executes it from the <projectname>\bin\Debug\net9.0 folder. It will be important to remember this when we work with the filesystem in later chapters. When using VS Code, or more accurately, the dotnet CLI, it has different behavior, as you are about to see.

Building console apps using VS Code

The goal of this section is to showcase how to build a console app using VS Code and the dotnet CLI.

If you never want to try VS Code or the dotnet command-line tool, then please feel free to skip this section, and then continue with the Making good use of the GitHub repository for this book section.

Both the instructions and screenshots in this section are for Windows, but the same actions will work with VS Code on the macOS 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, macOS, and Linux. Luckily, the dotnet CLI tool itself and its commands are identical on all platforms.

Writing code using VS Code

Let’s get started writing code!

  1. Start your favorite tool for working with the filesystem, for example, File Explorer on Windows or Finder on Mac.
  2. Navigate to your C: drive on Windows, your user folder on macOS or Linux (mine are named markjprice and home/markjprice), or any directory or drive in which you want to save your projects.
  3. Create a new folder named cs13net9. (If you completed the section for Visual Studio, then this folder will already exist.)
  4. In the cs13net9 folder, create a new folder named Chapter01-vscode.

If you did not complete the section for Visual Studio, then you could name this folder Chapter01, but I will assume you will want to complete both sections and, therefore, need to use a non-conflicting name.

  1. In the Chapter01-vscode folder, open the command prompt or terminal. For example, on Windows, right-click on the folder and then select Open in Terminal.
  2. At the command prompt or terminal, use the dotnet CLI to create a new solution named Chapter01, as shown in the following command:
    dotnet new sln --name Chapter01
    

You can use either -n or --name as the switch to specify a name. If you do not explicitly specify a solution name with one of these switches, then the default would match the name of the folder, for example, Chapter01-vscode.

  1. Note the result, as shown in the following output:
    The template "Solution File" was created successfully.
    
  2. At the command prompt or terminal, use the dotnet CLI to create a new subfolder and project for a console app named HelloCS, as shown in the following command:
    dotnet new console --output HelloCS
    

You can use either -o or --output as the switch to specify the folder and project name. The dotnet new console command targets your latest .NET SDK version by default. To target a different version, use the -f or --framework switch to specify a target framework. For example, to target .NET 8, use the following command: dotnet new console -f net8.0.

  1. At the command prompt or terminal, use the dotnet CLI to add the project to the solution, as shown in the following command:
    dotnet sln add HelloCS
    
  2. Note the results, as shown in the following output:
    Project `HelloCS\HelloCS.csproj` added to the solution.
    
  3. At the command prompt or terminal, start VS Code and open the current folder, indicated with a . (dot), as shown in the following command:
    code .
    
  4. If you are prompted with Do you trust the authors of the files in this folder?, select the Trust the authors of all files in the parent folder ‘cs13net9’ checkbox, and then click Yes, I trust the authors.
  5. In VS Code, in EXPLORER, in the CHAPTER01-VSCODE folder view, expand the HelloCS folder, and you will see that the dotnet command-line tool created two files, HelloCS.csproj and Program.cs, and the bin and obj folders, as shown in Figure 1.9:

Figure 1.9: EXPLORER shows that two files and temporary folders have been created

  1. Navigate to View | Output.
  2. In the OUTPUT pane, select C# Dev Kit, and note that the tool has recognized and processed the solution.
  3. At the bottom of EXPLORER, note SOLUTION EXPLORER.
  4. Drag SOLUTION EXPLORER to the top of the EXPLORER pane and expand it.
  5. In SOLUTION EXPLORER, expand the HelloCS project, and then click the file named Program.cs to open it in the editor window.
  6. In Program.cs, modify line 2 so that the text that is being written to the console says Hello, C#!.

Good Practice: Navigate to File | Auto Save. This toggle will avoid the annoyance of remembering to save before rebuilding your application each time.

In the preceding steps, I showed you how to use the dotnet CLI to create solutions and projects. Finally, with the August 2024 or later releases of the C# Dev Kit, VS Code has an improved project creation experience that provides you access to the same options you can use when creating a new project through the dotnet CLI.

To enable this ability, you must change a setting, as shown in the following configuration:

"csharp.experimental.dotnetNewIntegration": true

In VS Code, navigate to File | Preferences | Settings, search for dotnet new, and then select the Csharp > Experimental: Dotnet New Integration checkbox.

You can learn more at the following link:

https://devblogs.microsoft.com/dotnet/whats-new-in-csharp-dev-kit-august-2024/#create-new-project-configuration-options

Compiling and running code using the dotnet CLI

The next task is to compile and run the code:

  1. In SOLUTION EXPLORER, right-click on any file in the HelloCS project and choose Open In Integrated Terminal.
  2. In TERMINAL, enter the following command: dotnet run.
  3. The output in the TERMINAL window will show the result of running your application.
  4. In Program.cs, after the statement that outputs the message, add statements to get the name of the namespace of the Program class, write it to the console, and then throw a new exception, as shown in the following code:
    string name = typeof(Program).Namespace ?? "<null>";
    Console.WriteLine($"Namespace: {name}");
    throw new Exception();
    
  5. In TERMINAL, enter the following command: dotnet run.

In TERMINAL, you can press the up and down arrows to loop through previous commands, and then press the left and right arrows to edit the commands before pressing Enter to run them.

  1. The output in the TERMINAL window will show the result of running your application, including that a hidden Program class was defined by the compiler, with a method named <Main>$ that has a parameter named args to pass in arguments, and that it does not have a namespace, as shown in the following output:
    Hello, C#!
    Namespace: <null>
    Unhandled exception. System.Exception: Exception of type 'System.Exception' was thrown.
       at Program.<Main>$(String[] args) in C:\cs13net9\Chapter01-vscode\HelloCS\Program.cs:line 7
    

Adding a second project using VS Code

Let’s add a second project to explore how to work with multiple projects:

  1. In TERMINAL, change to the Chapter01-vscode directory, as shown in the following command:
    cd ..
    
  2. In TERMINAL, create a new console app project named AboutMyEnvironment, using the older non-top-level program style, as shown in the following command:
    dotnet new console -o AboutMyEnvironment --use-program-main
    

Good Practice: Be careful when entering commands in TERMINAL. Ensure that you are in the correct folder before entering potentially destructive commands!

  1. In TERMINAL, use the dotnet CLI to add the new project folder to the solution, as shown in the following command:
    dotnet sln add AboutMyEnvironment
    
  2. Note the results, as shown in the following output:
    Project `AboutMyEnvironment\AboutMyEnvironment.csproj` added to the solution.
    
  3. In SOLUTION EXPLORER, in the AboutMyEnvironment project, open Program.cs, and then in the Main method, change the existing statement to output the current directory, the operating system version string, and the namespace of the Program class, as shown in the following code:
    Console.WriteLine(Environment.CurrentDirectory);
    Console.WriteLine(Environment.OSVersion.VersionString);
    Console.WriteLine("Namespace: {0}",
      typeof(Program).Namespace ?? "<null>");
    
  4. In SOLUTION EXPLORER, right-click on any file in the AboutMyEnvironment project and choose Open In Integrated Terminal.
  5. In TERMINAL, enter the command to run the project, as shown in the following command: dotnet run.
  6. Note the output in the TERMINAL window, as shown in the following output:
    C:\cs13net9\Chapter01-vscode\AboutMyEnvironment
    Microsoft Windows NT 10.0.26100.0
    Namespace: AboutMyEnvironment
    

Once you open multiple terminal windows, you can toggle between them by clicking their names in the panel on the right-hand side of TERMINAL. By default, the name will be one of the common shells like pwsh, powershell, zsh, or bash. Right-click and choose Rename to set something else.

When VS Code, or more accurately, the dotnet CLI, runs a console app, it executes it from the <projectname> folder. Visual Studio executes the app from the <projectname>\bin\Debug\net9.0 folder. It will be important to remember this when we work with the filesystem in later chapters.

If you were to run the program on macOS Ventura, the environment operating system would be different, as shown in the following output:

Unix 13.5.2

Good Practice: Although the source code, like the .csproj and .cs files, is identical, the bin and obj folders that are automatically generated by the compiler could have mismatches that give you errors. If you want to open the same project in both Visual Studio and VS Code, delete the temporary bin and obj folders before opening the project in the other code editor. This potential problem is why I asked you to create a different folder for the VS Code projects in this chapter.

Summary of steps for VS Code

Follow these steps to create a solution and projects using VS Code, as shown in Table 1.5:

Step Description

Command

1. Create a folder for the solution.

mkdir <solution_folder_name>

2. Change to the folder.

cd <solution_folder_name>

3. Create a solution file in the folder.

dotnet new sln

4. Create a folder and project using a template.

dotnet new console -o <project_folder_name>

5. Add the folder and its project to the solution.

dotnet sln add <project_folder_name>

6. Repeat steps 4 and 5 to create and add any other projects.

7. Open the current folder path (.) containing the solution using VS Code.

code .

Table 1.5: Summary of steps to create a solution and projects using VS Code

Summary of other project types used in this book

A Console App / console project is just one type of project template. In this book, you will also create projects using the following project templates, as shown in Table 1.6:

Visual Studio

dotnet new

Rider – Type

Console App

console

Console Application

Class Library

classlib

Class Library

xUnit Test Project

xunit

Unit Test Project – xUnit

ASP.NET Core Empty

web

ASP.NET Core Web Application – Empty

Blazor Web App

blazor

ASP.NET Core Web Application – Blazor Web App

ASP.NET Core Web API

webapi

ASP.NET Core Web Application – Web API

ASP.NET Core Web API (native AOT)

webapiaot

ASP.NET Core Web Application – Web API (native AOT)

Table 1.6: Project template names for various code editors

The steps for adding any type of new project to a solution are the same. Only the type name of the project template differs and, sometimes, some command-line switches to control options. I will always specify what those switches and options should be if they differ from the defaults.

A summary of project template defaults, options, and switches can be found here: https://github.com/markjprice/cs13net9/blob/main/docs/ch01-project-options.md.

Making good use of the GitHub repository for this book

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 created a GitHub repository for this book, and I use it for the following:

  • To store the solution code for the book that can be maintained after the print publication date.
  • To provide extra materials that extend the book, like errata fixes, small improvements, lists of useful links, and optional sections about topics that cannot fit in the printed book.
  • To provide a place for readers to get in touch with me if they have issues with the book.

Good Practice: I strongly recommend that you all review the errata, improvements, post-publication changes, and common errors pages before attempting any coding task in this book. You can find them at the following link: https://github.com/markjprice/cs13net9/blob/main/docs/errata/README.md.

Understanding the solution code on GitHub

The solution code in the GitHub repository for this book includes folders for each chapter that can be opened with any of the following code editors:

  • Visual Studio or Rider: Open the .sln solution file.
  • VS Code: Open the folder that contains the solution file.

Chapters 1 to 11 each have their own solution file named ChapterXX.sln, where XX is the chapter number 01 to 11. Chapters 12 to 15 share a single solution file named ModernWeb.sln.

The .sln solution file format is a Microsoft proprietary file format that is verbose, hard to read, and uses Globally Unique Identifiers (GUIDs) to reference projects and other components of a solution. A new format based on XML, designed to be simpler and easier to read, is coming soon and will use the .slnx file extension. You can learn more about this at the following link: https://github.com/dotnet/sdk/issues/40913.

All the code solutions can be found at the following link:

https://github.com/markjprice/cs13net9/tree/main/code

Good Practice: If you need to, return to this chapter to remind yourself how to create and manage multiple projects in the code editor of your choice. The GitHub repository has step-by-step instructions for three code editors (Visual Studio, VS Code, and Rider), along with additional screenshots: https://github.com/markjprice/cs13net9/tree/main/docs/code-editors/.

Raising issues with the book

If you get stuck following any of the instructions in this book, or if you spot a mistake in the text or the code in the solutions, please raise an issue in the GitHub repository:

  1. Use your favorite browser to navigate to the following link: https://github.com/markjprice/cs13net9/issues.
  2. Click New Issue.
  3. Enter as much detail as possible that will help me to diagnose the issue. For example:
    • The specific section title, page number, and step number.
    • As much of your code and configuration that you feel is relevant and necessary.
    • A description of the expected behavior and the behavior experienced.
    • Screenshots (you can drag and drop image files into the Issue box).

The following is less relevant but might be useful:

  • Your code editor, for example, Visual Studio, VS Code, Rider, or something else, including the version number.
  • Your operating system, for example, Windows 11 64-bit or macOS Ventura version 13.5.2
  • Your hardware, for example, Intel, Apple Silicon, or ARM CPU

I cannot always respond immediately to issues. But I want all my readers to find success with my book, so if I can help you (and others) without too much trouble, then I will gladly do so.

Giving me feedback

If you’d like to give me more general feedback about the book, then either email me at markjprice@gmail.com or ask me a question on Discord in the book channel. You can provide the feedback anonymously, or if you would like a response from me, then you can supply an email address. I will only use this email address to answer your feedback.

Please join me and your fellow readers on Discord using this invite: https://packt.link/csharp13dotnet9.

I love to hear from my readers about what they like about my book, as well as suggestions for improvements and how they are working with C# and .NET, so don’t be shy. Please get in touch!

Thank you in advance for your thoughtful and constructive feedback.

Avoiding common mistakes

After working through the step-by-step tasks in this book, readers often then strike out on their own and attempt to write similar code, but sometimes, they hit problems and either raise an issue in the GitHub repository or post a question to the Discord channel for the book.

From these, I have noted some common mistakes, so I maintain a page in the repository to highlight and explain these potential traps and how to fix them:

https://github.com/markjprice/cs13net9/blob/main/docs/errata/common-mistakes.md

Downloading solution code from the GitHub repository

If you just want to download all the solution files without using Git, click the green <> Code button and then select Download ZIP, as shown in Figure 1.10:

Figure 1.10: Downloading the repository as a ZIP file

Good Practice: It is best to clone or download the code solutions to a short folder path, like C:\cs13net9\ or C:\book\, to avoid build-generated files that exceed the maximum path length. You should also avoid special characters like #. For example, do not use a folder name like C:\C# projects\. That folder name might work for a simple console app project, but once you start adding features that automatically generate code, you are likely to have strange issues. Keep your folder names short and simple.

Using Git with VS Code and the command prompt

VS Code has integrations with Git, but it will use your operating system’s Git installation, so you must install Git 2 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: https://desktop.github.com.

Cloning the book solution code repository

Let’s clone the book solution code repository. In the steps that follow, you will use the VS Code terminal, but you can enter the commands at any command prompt or terminal window:

  1. Create a folder named Repos-vscode in your user or Documents folder, or wherever you want to store your Git repositories.
  2. Open the Repos-vscode folder at the command prompt or terminal, and then enter the following command:
    git clone https://github.com/markjprice/cs13net9.git
    

Note that cloning all the solutions for all the chapters will take a minute or so, so please be patient.

Looking for help

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

Microsoft Learn documentation and Ask Learn

The definitive resource for getting help with Microsoft developer tools and platforms is in the technical documentation on Microsoft Learn, and you can find it at the following link: https://learn.microsoft.com/en-us/docs.

“One of the most ambitious and impactful projects our engineers have built recently is Ask Learn, an API that provides generative AI capabilities to Microsoft Q&A.” - Bob Tabor, Microsoft’s Skilling organization

You can read about it at the following link:

https://devblogs.microsoft.com/engineering-at-microsoft/how-we-built-ask-learn-the-rag-based-knowledge-service/

Documentation links in this book

The official Microsoft documentation for .NET needs to cover all versions. The default version shown in the documentation is always the most recent GA version.

For example, between November 2024 and November 2025, the default version of .NET shown in the documentation pages will be for .NET 9. Between November 2025 and November 2026, the default version of .NET will be for .NET 10. The following link will automatically direct to the current version, depending on the current date:

https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.stringsyntaxattribute

After November 2025, to view the documentation page specifically for .NET 9, append ?view=net-9.0 to the end of a link. For example, use the following link:

https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.stringsyntaxattribute?view=net-9.0

All documentation links in this book do not specify a version. If you want to force the documentation to show the version for .NET 8 because you need to target an LTS version (three years) instead of .NET 9, which is an STS version (18 months), then append ?view=net-8.0 to the end of a link.

You can check what versions a .NET feature supports by appending #applies-to to the end of a link, for example:

https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.stringsyntaxattribute#applies-to

We can, therefore, see that the StringSyntax attribute is only available in .NET 7 or later.

Getting help from the dotnet tool

At the command prompt, you can ask the dotnet tool for help with its commands. The syntax is:

dotnet help <command>

This will cause your web browser to open a page in the documentation about the specified command. Common dotnet commands include new, build, run, and many more.

Warning! The dotnet help new command worked with .NET Core 3.1 to .NET 6, but it returns an error with .NET 7 or later: Specified command 'new' is not a valid SDK command. Specify a valid SDK command. For more information, run dotnet help. Hopefully, .NET will fix that bug soon!

Another type of help is command-line documentation. It follows this syntax:

dotnet <command> -?|-h|--help

For example, dotnet new -? or dotnet new -h or dotnet new --help outputs documentation about the new command at the command prompt.

As you should now expect, dotnet help help opens a web browser for the help command, and dotnet help -h outputs documentation for the help command at the command prompt!

Let’s try some examples:

  1. To open the official documentation in a web browser window for the dotnet build command, enter the following at the command prompt or in the VS Code terminal, and note the page opened in your web browser:
    dotnet help build
    
  2. To get help output at the command prompt, use the -? or -h or --help flag, as shown in the following command:
    dotnet build -?
    
  3. You will see the following partial output:
    Description:
      .NET Builder
    Usage:
      dotnet build [<PROJECT | SOLUTION>...] [options]
    Arguments:
      <PROJECT | SOLUTION>  The project or solution file to operate on. If a file is not specified, the command will search the current directory for one.
    Options:
      --ucr, --use-current-runtime         Use current runtime as the target runtime.
      -f, --framework <FRAMEWORK>          The target framework to build for. The target framework must also be specified in the project file.
    ...
      -?, -h, --help                       Show command line help.
    
  4. Repeat both types of help requests for the following commands: add, help, list, new, and run, remembering that new might not show its web page, due to a bug introduced in .NET 7.

Getting definitions of types and their members

One of the most useful features of a code editor is Go To Definition (F12). It is available in VS Code, Visual Studio, and Rider. It 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 the metadata and IL code back into C# or another language for you.

A similar and related feature is named Go To Implementation (Ctrl + F12). Instead of reading the metadata or decompiling, this will show the actual source code if that is embedded, using the optional source link feature.

Warning! Go To Definition should go to the decompiled metadata for a member or type. But if you have previously viewed the source link, then it goes to that. Go To Implementation should go to the source link implementation for a member or type. But if you have disabled the source link, then it goes to the decompiled metadata.

Let’s see how to use the Go To Definition feature:

  1. In your preferred code editor, open the solution/folder named Chapter01.

If you are using Visual Studio:

  • Navigate to Tools | Options.
  • In the search box, enter navigation to source.
  • Select Text Editor | C# | Advanced.
  • Clear the Enable navigation to Source Link and Embedded sources checkbox, and then click OK, as shown in Figure 1.11:

Figure 1.11: Disabling Source Link for the Go To Definition feature

Definitions can be either reverse-engineered from metadata or loaded from the original source code if that is enabled. Personally, I find the code from metadata more useful, as you are about to see. At the end of this section, try switching the Source Link option back on to see the difference.

  1. In the HelloCS project, at the bottom of Program.cs, enter the following statement to declare an integer variable named z:
    int z;
    
  2. Click on int, right-click on int, and then choose Go To Definition in Visual Studio or VS Code. In Rider, choose Go to | Go to Declaration or Usages.
  3. In the code window that appears, you can see how the int data type is defined, as shown in the following code:
    #region Assembly System.Runtime, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
    // C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\9.0.0\ref\net9.0\System.Runtime.dll
    #endregion
    #nullable enable
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Numerics;
    using System.Runtime.CompilerServices;
    namespace System
    {
      public readonly struct Int32 : IComparable,
        IComparable<Int32>, IConvertible, ...
      {
        public const Int32 MaxValue = 2147483647;
        public const Int32 MinValue = -2147483648;
        ...
      }
    }
    

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 (2147483647) and minimum (-2147483648) values.
  • Has methods such as Parse (not visible in the preceding code).

Currently, the Go To Definition feature is not that useful to you because you do not yet know what all of this information means. By the end of the first part of this book, which consists of Chapters 2 to 6 and teaches you about the C# language, 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, as shown in the following code:
    public static Int32 Parse(string s)
    
  2. Expand the code and review the comments that document this method, as shown in Figure 1.12:

Figure 1.12: The comments for the Parse method with a single string parameter

In the comments, you will see that Microsoft has documented the following:

  • A summary that describes the method.
  • Parameters like the string value that can be passed to the method.
  • The return value of the method, including its data type.
  • Three exceptions that might occur if you call this method, including ArgumentNullException, FormatException, and OverflowException. Now, we know that we could choose to wrap a call to this method in a try statement and which exceptions to catch.

Configuring inline aka inlay hints

Throughout the code in this book, when calling a method, I often explicitly specify named parameters to help you learn what is going on. For example, I have specified the names of the parameters format and arg0 in the following code:

Console.WriteLine(format: "Value is {0}.", arg0: 19.8);

Inline hints, aka inlay hints, show the names of parameters without you having to type them, as shown in Figure 1.13:

Figure 1.13: Configuring inline hints, aka inlay hints

Most code editors have this feature, which you can enable permanently or only when a key combination like Alt + F1 or Ctrl is held down:

  • In Visual Studio, navigate to Tools | Options, then Text Editor | C# | Advanced, scroll down to the Inline Hints section, select the Display inline parameter name hints checkbox, and then click OK.
  • In VS Code, navigate to File | Preferences | Settings, search for inlay, select the C# filter, and then select the Display inline parameter name hints checkbox.
  • In Rider, in Settings, navigate to Editor | Inlay Hints | C# | Parameter Name Hints.

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. Let’s see an example:

  1. Start your favorite web browser.
  2. Navigate to stackoverflow.com; in the search box, enter securestring and note the search results.

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 at the following link: https://www.google.com/.
  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, 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
    

Getting help on Discord and other chat forums

Asking questions in programming forums and Discord channels is an art as much as it is a science. To maximize your chances of receiving a helpful answer, there’s a blend of clarity, specificity, and community awareness that you should aim for.

Here are some tips for asking questions:

  • Ask in a public channel, not in private. Please do not direct message an author with a question or a friend request. Remember, every question asked and answered builds the collective knowledge and resourcefulness of the whole community. Asking in public also allows other readers to help you, not just the author. The community that Packt and I have built around my books is friendly and smart. Let us all help you.
  • Research before asking: It’s important to look for answers yourself before turning to the community. Use search engines, official documentation, and the search function within the forum or Discord server. This not only respects the community’s time but also helps you learn more effectively. Another place to look first is the errata and improvements section of the book, found at the following link: https://github.com/markjprice/cs13net9/blob/main/docs/errata/README.md.
  • Be specific and concise: Clearly state what you’re trying to achieve, what you’ve tried so far, and where you’re stuck. A concise question is more likely to get a quick response.
  • Specify the book location: If you are stuck on a particular part of the book, specify the page number and section title so that others can look up the context of your question.
  • Show your work: Demonstrating that you’ve made an effort to solve the problem yourself not only provides context but also helps others understand your thought process and where you might have gone down a wrong path.
  • Prepare your question: Avoid too broad or vague questions. Screenshots of errors or code snippets (with proper formatting) can be very helpful.

    Oddly, I’ve been seeing more and more examples of readers taking photos of their screens and posting those. These are harder to read and limited in what they can show. It’s better to copy and paste the text of your code or the error message so that others can copy and paste it themselves. Alternatively, at least take a high-resolution screenshot instead of a photo with your phone camera at a jaunty angle!

  • Format your code properly: Most forums and Discord servers support code formatting using Markdown syntax. Use formatting to make your code more readable. For example, surround code keywords in single backticks, like `public void`, and surround code blocks with three backticks with optional language code, as shown in the following code:
    ```cs
    using static System.Console;
    WriteLine("This is C# formatted code.");
    ```
    

    Good Practice: After the three backticks that start a code block in Markdown, specify a language short name like cs, csharp, js, javascript, json, html, css, cpp, xml, mermaid, python, java, ruby, go, sql, bash, or shell.

More Information: To learn how to format text in Discord channel messages, see the following link: https://support.discord.com/hc/en-us/articles/210298617-Markdown-Text-101-Chat-Formatting-Bold-Italic-Underline.

  • Be polite and patient: Remember, you’re asking for help from people who are giving their time voluntarily. A polite tone and patience while waiting for a response go a long way. Channel participants are often in a different time zone, so you may not see your question answered until the next day.
  • Be ready to actively participate: After asking your question, stay engaged. You might receive follow-up questions for clarification. Responding promptly and clearly can significantly increase your chances of getting a helpful answer. When I ask a question, I set an alarm for three hours later to go back and see if anyone has responded. If there hasn’t been a response yet, then I set another alarm for 24 hours later.

Incorporating these approaches when asking questions not only increases your likelihood of getting a useful response but also contributes positively to the community, by showing respect for others’ time and effort.

Good Practice: Never just say “Hello” as a message on any chat system. You can read why at the following link: https://nohello.net/. Similarly, don’t ask to ask: https://dontasktoask.com/.

Searching the .NET source code

Sometimes, you can learn a lot from seeing how the Microsoft teams have implemented .NET. The source for the entire code base for .NET is available in public GitHub repositories. For example, you might know that there is a built-in attribute to validate an email address.

Let’s search the repositories for the word “email” and see if we can find out how it works:

  1. Use your preferred web browser to navigate to https://github.com/search.
  2. Click advanced search.
  3. In the search box, type email.
  4. In the In these respositories box, type dotnet/runtime. (Other repositories that you might want to search include dotnet/core, dotnet/aspnetcore, dotnet/wpf, and dotnet/winforms.)
  5. In the Written in this language box, select C#.
  6. At the top right of the page, note how the advanced query has been written for you. Click Search, then the Code filter, and note that the results include EmailAddressAttribute, as shown in Figure 1.14:

Figure 1.14: Advanced search for email in the dotnet/runtime repository

  1. Click the source file, and note that it implements email validation by checking that the string value contains an @ symbol but not as the first or last character, as shown in the following code:
    // only return true if there is only 1 '@' character
    // and it is neither the first nor the last character
    int index = valueAsString.IndexOf('@');
    return
        index > 0 &&
        index != valueAsString.Length - 1 &&
        index == valueAsString.LastIndexOf('@');
    
  2. Close the browser.

For your convenience, you can do a quick search for other terms by replacing the search term email in the following link: https://github.com/search?q=%22email%22+repo%3Adotnet%2Fruntime+language%3AC%23&type=code&ref=advsearch.

Source code in documentation

When you read API reference documentation, you often want to review the actual source code. For .NET APIs that have Source Link enabled, have an accessible PDB, and are hosted in a public GitHub repository, links to source code are included in the definition metadata. For example, the String class documentation page now has this new Source link, and its IndexOf method has a Source link to another of its source files, as shown in Figure 1.15:

A screenshot of a computer

Description automatically generated

Figure 1.15: Documentation with links to source files

You can read more about how the Microsoft team achieved this in the article Introducing links to source code for .NET API Docs, found at the following link: https://devblogs.microsoft.com/dotnet/dotnet-docs-link-to-source-code/.

Official .NET blog, standups, and news

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/.

To watch .NET team members walk through previews of new features, you can watch monthly “standups,” available at the following link:

https://dotnet.microsoft.com/en-us/live/community-standup

You can subscribe to the latest .NET news at the following link:

https://github.com/dotnet/core/discussions/categories/news

Watching Scott Hanselman’s videos

Scott Hanselman from Microsoft has an excellent YouTube channel about computer stuff that they didn’t teach you at school: http://computerstufftheydidntteachyou.com/.

I recommend it to everyone working with computers.

AI tools like ChatGPT and GitHub Copilot

One of the biggest changes in coding and development in the past few years is the emergence of generative artificial intelligence (AI) tools that can help with coding tasks, like completing a code statement, implementing an entire function, writing unit tests, and suggesting debugging fixes for existing code.

You can read what developers say about AI tools in the 2023 Stack Overflow Developer Survey: “44% of them use AI tools in their development process now, and 26% plan to soon” (https://stackoverflow.blog/2023/06/14/hype-or-not-developers-have-something-to-say-about-ai/):

“From research to debugging to documentation, developers are using Generative AI to save time doing various tedious tasks at work. The biggest use case is writing code. This was how 82.55% of developers reported using Generative AI in the recent Stack Overflow Developer Survey.”

ChatGPT currently has several models for individuals: 4o mini (free), 4o (free but limited), and 4o with 5x more requests and other benefits, like early access to new features and DALL·E image generation ($20 per month). It also has pricing for enterprises. You can check their pricing at the following link: https://openai.com/chatgpt/pricing/.

ChatGPT example

Let’s say you need to write a C# function to validate an email address. You might go to ChatGPT and enter the following prompt:

write a c# function to validate an email address

It responds with a complete class with methods, as shown in Figure 1.16:

Figure 1.16: ChatGPT writes a function to validate an email address

It then provides an explanation of the code and examples of how to call the function, as shown in the following code:

bool isValid = EmailValidator.IsValidEmail("test@example.com");
Console.WriteLine(isValid ? "Valid" : "Invalid");

But is a general-purpose generative AI like ChatGPT the best partner for a C# programmer?

GitHub Copilot for programmers

Microsoft has a service specifically for programmers, named GitHub Copilot, that can help autocomplete code directly in your code editor. It has plugins for code editors, including Visual Studio, VS Code, and JetBrains IntelliJ-based IDEs.

Personally, I really like the Copilot branding. It makes it clear that you are the pilot. You are ultimately responsible for “flying the plane.” But for the easy or boring bits, you can hand it over to your co-pilot for a bit, while being actively ready to take back control if needed.

GitHub Copilot is free for students, teachers, and some open-source project maintainers. For everyone else, it has a 30-day free trial, and then it costs $10 per month or $100 per year for individuals. Once you have an account, you can then sign up for waiting lists to get the more advanced experimental GitHub Copilot features.

You should check online which Copilot features are available for various code editors. As you can imagine, this is a fast-changing world, and some of what I might write in the book today will be out of date by the time you read it: https://github.com/features/copilot.

JetBrains has its own GitHub Copilot equivalent, named AI Assistant, which you can read about at the following link: https://blog.jetbrains.com/idea/2023/06/ai-assistant-in-jetbrains-ides/.

So what can GitHub Copilot do for you today?

Imagine that you have just added a new class file named Product.cs. You click inside the Product class, press Enter to insert a blank line, and then pause for a second as you think about what you need to type… and then GitHub Copilot generates some sample code in gray, as shown in Figure 1.17:

Figure 1.17: GitHub Copilot suggesting how to define a Product class

At this point, you can glance over the code and, if it is close to what you want, just press Tab to insert it all, or press Alt + . (dot) to toggle between other suggestions.

Sometimes, it is too far from what you need, and you’d be better off ignoring its suggestion completely and just writing it yourself. But usually, there’s something there that’s usable or reminds you of the syntax you need to use. And sometimes, it feels like magic, writing dozens of lines of exactly what you need.

Microsoft feeds its AI tools with code from public GitHub repositories, including all the repositories I have created since 2016 for all the editions of this book. This means that it can suggest code completions for the readers of this book that are surprisingly accurate predictions, including my frequent use of pop culture references in my code. It’s like I, Mark J. Price, am the “ghost in the machine” guiding your coding.

It’s easy to imagine a custom ChatGPT that has ingested all the official Microsoft .NET documentation, every public blog article written about .NET, and perhaps even hundreds of books about .NET, and then having a conversation with it to find a bug or suggest how to solve a programming problem.

You can sign up for GitHub Copilot at the following link: https://github.com/github-copilot/signup/.

Good Practice: Learn more about how to use Copilot as your coding GPS at the following link: https://devblogs.microsoft.com/visualstudio/using-github-copilot-as-your-coding-gps/.

Here are some more links about using AI for coding:

Disabling tools when they get in the way

Although these tools can be helpful, they can also get in your way, especially when learning, because they sometimes do work for you without telling you. If you do not do that work for yourself at least a few times, you won’t learn fully.

To configure IntelliSense for C# in Visual Studio:

  1. Navigate to Tools | Options.
  2. In the Options dialog box tree view, navigate to Text Editor | C# | IntelliSense.
  3. Click the ? button in the caption bar to view the documentation.

To configure GitHub Copilot in Visual Studio:

  1. Navigate to Tools | Options.
  2. In the Options dialog box tree view, navigate to GitHub | Copilot.
  3. Set Enable Globally to True or False, and then click OK.

To disable GitHub Copilot in VS Code:

  1. In the status bar, on the right, to the left of the notification icon, click the GitHub Copilot icon.
  2. In the popup, click Disable Globally.
  3. To enable it, click the GitHub Copilot icon again and then click Enable Globally.

For help with Rider IntelliSense, please see the following link: https://www.jetbrains.com/help/rider/Auto-Completing_Code.html.

Practicing and exploring

Let’s now test your knowledge and understanding by trying to answer some questions, getting some hands-on practice, and going into the topics covered throughout this chapter in greater detail.

Exercise 1.1 – Online material

Online material can be extra content written by me for this book, or it can be references to content created by Microsoft or third parties.

Current versions of .NET

You can check what the latest version of .NET is for various platforms and what is officially supported at the following link: https://versionsof.net.

If you need to know more about support for the legacy .NET Framework, you can read about it at the following link: https://learn.microsoft.com/en-us/lifecycle/products/microsoft-net-framework.

Upgrade to a new .NET version

.NET releases new versions annually. Some developers begin upgrading as soon as a new version drops, while others prefer to wait until their current version reaches end-of-support. Upgrading involves several important considerations that you can read about at the following link:

https://learn.microsoft.com/en-us/dotnet/core/install/upgrade

freeCodeCamp and C# certification

For many years, Microsoft had an exam for C# 5, Exam 70-483: Programming in C#. I taught hundreds of developers the skills needed to get qualified and pass it. Sadly, that exam was retired a few years ago.

In August 2023, Microsoft announced a new foundational certification for C# alongside a free 35-hour online course. You can read more about how to qualify for the certification at the following link:

https://www.freecodecamp.org/learn/foundational-c-sharp-with-microsoft/

C# certification signup: https://aka.ms/learningseries/csharp/signup

Explore Polyglot Notebooks

Complete the following online-only section to explore how you can use Polyglot Notebooks with its .NET Interactive engine:

https://github.com/markjprice/cs13net9/blob/main/docs/ch01-polyglot-notebooks.md

Windows development

This book is about modern cross-platform development. But what about graphical user interface (GUI) development especially for Windows?

You can read an article discussing this at the following link:

https://visualstudiomagazine.com/articles/2024/02/13/desktop-dev.aspx

C# versus other languages

Even Microsoft does not use C# and .NET for all its own development needs. You can read an interesting discussion about C# and Rust at the following link:

https://www.reddit.com/r/dotnet/comments/1aezqmg/comment/ko8lnf2/

The key quote at the preceding Reddit link is this:

“There’s been a lot of hype around Rust, and for good reason. But it’s a system language. It’s not like Microsoft is about to go rewrite millions and millions of lines of code and toss out C# (for anyone getting nervous ). They’re just being pragmatic and using an effective tool for the job.”

Free computer science course

Harvard CS50: Introduction to Computer Science: https://pll.harvard.edu/course/cs50-introduction-computer-science

.NET newsletters

There are email newsletters that you can subscribe to get daily or weekly updates, hints, and tips. Some of the better ones include the following:

Exercise 1.2 – Practice exercises

The following practice exercises will go deeper into the topics for this chapter.

Practice C# anywhere with a browser

You don’t need to download and install VS Code or even Visual Studio to write C#. You can start coding online at any of the following links:

Alpha versions of .NET

You can (but probably shouldn’t) download future versions of .NET, including alpha versions from the following link:

https://github.com/dotnet/sdk/blob/main/documentation/package-table.md

Warning! Alpha versions are designed to be used only internally by Microsoft employees. Beta versions (official previews) are designed to be used externally and become available from mid-February each year.

For more about using .NET 10 with this book, please see the following link: https://github.com/markjprice/cs13net9/blob/main/docs/dotnet10.md.

Exercise 1.3 – Test your knowledge

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

  1. Is Visual Studio better than VS Code?
  2. Are .NET 5 and later versions better than .NET Framework?
  3. What is .NET Standard, and why is it still important?
  4. Why can a programmer use different languages (for example, C# and F#) to write applications that run on .NET?
  5. What is a top-level program, and how do you access any command-line arguments?
  6. What is the name of the entry point method of a .NET console app, and how should it be explicitly declared if you are not using the top-level program feature?
  7. What namespace is the Program class defined in with a top-level program?
  8. Where would you look for help for a C# keyword?
  9. Where would you look first for solutions to common programming problems?
  10. What should you do after getting AI to write code for you?

Appendix, Answers to the Test Your Knowledge Questions, is available to download from a link in the README file in the GitHub repository: https://github.com/markjprice/cs13net9.

Exercise 1.4 – Explore topics

A printed book is a curated experience. I have tried to find the right balance of topics to include in this book. Other content that I have written can be found in the GitHub repository for this book.

I believe that this book covers all the fundamental knowledge and skills a C# and .NET developer should have or be aware of. Some longer examples are best included as links to Microsoft documentation or third-party article authors.

Use the links on the following page to learn more details about the topics covered in this chapter:

https://github.com/markjprice/cs13net9/blob/main/docs/book-links.md#chapter-1---hello-c-welcome-net

Summary

In this chapter, we:

  • Set up your development environment.
  • Discussed the similarities and differences between modern .NET, .NET Core, .NET Framework, Xamarin, and .NET Standard in an online article.
  • Used Visual Studio and VS Code with the .NET SDK CLI to create a couple of simple console apps, grouped in a solution.
  • Learned how to download the solution code for this book from its GitHub repository.
  • Learned how to find help. This could be in the traditional way, by using help command switches, documentation, and articles, or the modern way, by having a conversation with coding expert AI or using an AI-based tool to perform “grunt work.”

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

Learn more on Discord

To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below:

https://packt.link/csharp13dotnet9

Leave a Review!

Thank you for purchasing this book from Packt Publishing—we hope you enjoy it! Your feedback is invaluable and helps us improve and grow. Once you’ve completed reading it, please take a moment to leave an Amazon review; it will only take a minute, but it makes a big difference for readers like you.

Scan the QR or visit the link to receive a free ebook of your choice.

https://packt.link/NzOWQ

A qr code with black squares

Description automatically generated

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore the newest additions to C# 13, the .NET 9 class libraries, and Entity Framework Core 9
  • Build professional websites and services with ASP.NET Core 9 and Blazor
  • Enhance your skills with step-by-step code examples and best practices tips

Description

This Packt bestseller continues to be the definitive guide to modern cross-platform development. The 9th edition of C# 13 and .NET 9 – Modern Cross-Platform Development Fundamentals has been updated to cover the latest features and improvements in .NET 9 and C# 13. You'll start by mastering object-oriented programming, learning how to write, test, and debug functions, and implementing interfaces. You'll then dive into .NET APIs for data management, filesystem operations, and serialization. This latest edition integrates .NET 9 enhancements into its examples: faster exceptions and new LINQ methods. New ASP.NET Core 9 features include optimized static assets, built-in OpenAPI document generation, and the HybridCache. Practical examples, such as building websites and services with ASP.NET Core, have been refreshed to utilize the latest .NET 9 features. The book also introduces Blazor, with its new unified hosting model for unparalleled code reusability. With these updates, you'll learn how to build robust applications and services efficiently and effectively. By the end of this book, you'll have the knowledge and confidence to create professional and high-performance web applications using the latest technologies in C# 13 and .NET 9.

Who is this book for?

This book is aimed at beginner to intermediate-level C# and .NET developers. While prior exposure to C# or .NET is not a prerequisite, a general understanding of programming concepts will be beneficial. If you want to learn more technologies for building modern .NET projects like gRPC, SignalR, and .NET MAUI, read Mark's Apps and Services with .NET 8 book next; and if you aim to become a professional .NET developer quickly or mainly work on team projects, read his other book, Tools and Skills for .NET 8.

What you will learn

  • Discover the new features of .NET 9, including more flexible params and new LINQ like CountBy and Index
  • Leverage the new ASP.NET Core 9 features for optimized static assets, OpenAPI document generation, and HybridCache
  • Utilize the native AOT publish capability for faster startup and reduced memory footprint
  • Build rich web user interface experiences using Blazor in ASP.NET Core 9
  • Integrate and update databases in your applications using Entity Framework Core 9 models
  • Query and manipulate data using LINQ
  • Build powerful services using Minimal APIs

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 12, 2024
Length: 828 pages
Edition : 9th
Language : English
ISBN-13 : 9781835881231
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 12, 2024
Length: 828 pages
Edition : 9th
Language : English
ISBN-13 : 9781835881231
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Table of Contents

17 Chapters
Hello, C#! Welcome, .NET! Chevron down icon Chevron up icon
Speaking C# Chevron down icon Chevron up icon
Controlling Flow, Converting Types, and Handling Exceptions Chevron down icon Chevron up icon
Writing, Debugging, and Testing Functions Chevron down icon Chevron up icon
Building Your Own Types with Object-Oriented Programming Chevron down icon Chevron up icon
Implementing Interfaces and Inheriting Classes Chevron down icon Chevron up icon
Packaging and Distributing .NET Types Chevron down icon Chevron up icon
Working with Common .NET Types Chevron down icon Chevron up icon
Working with Files, Streams, and Serialization Chevron down icon Chevron up icon
Working with Data Using Entity Framework Core Chevron down icon Chevron up icon
Querying and Manipulating Data Using LINQ Chevron down icon Chevron up icon
Introducing Modern Web Development Using .NET Chevron down icon Chevron up icon
Building Websites Using ASP.NET Core Chevron down icon Chevron up icon
Building Interactive Web Components Using Blazor Chevron down icon Chevron up icon
Building and Consuming Web Services Chevron down icon Chevron up icon
Epilogue Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.