35,99 €
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.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 1113
Veröffentlichungsjahr: 2024
C# 13 and .NET 9 – Modern Cross-Platform Development Fundamentals
Ninth Edition
Start building websites and services with ASP.NET Core 9, Blazor, and EF Core 9
Mark J. Price
C# 13 and .NET 9 – Modern Cross-Platform Development Fundamentals
Ninth Edition
Copyright © 2024 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Senior Publishing Product Manager: Suman Sen
Acquisition Editor – Peer Reviews: Jane D'Souza
Project Editor: Janice Gonsalves
Content Development Editor: Shazeen Iqbal
Copy Editor: Safis Editing
Technical Editor: Simanta Rajbangshi
Proofreader: Safis Editing
Indexer: Rekha Nair
Presentation Designer: Pranit Padwal
Developer Relations Marketing Executive: Priyadarshini Sharma
First published: March 2016
Second edition: March 2017
Third edition: November 2017
Fourth edition: October 2019
Fifth edition: November 2020
Sixth edition: November 2021
Seventh edition: November 2022
Eighth edition: November 2023
Ninth edition: November 2024
Production reference: 1071124
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK.
ISBN 978-1-83588-122-4
www.packt.com
Mark J. Price is a Microsoft Specialist: Programming in C# and Architecting Microsoft Azure Solutions, with over 20 years of experience. Since 1993, he has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them. Between 2001 and 2003, Mark was employed to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught “train-the-trainer” classes to get Microsoft Certified Trainers up-to-speed on C# and .NET. Mark has spent most of his career training a wide variety of students from 16-year-old apprentices to 70-year-old retirees, with the majority being professional developers. Mark holds a BSc in Computer Science.
Thank you to all my readers. Your support means I get to write these books and celebrate your successes.
Special thanks to the readers who give me actionable feedback via my GitHub repository and email and interact with me and the book communities on Discord. You help make my books even better with every edition.
Extra special thanks to Alex, who brings joy and comfort to my life.
Kieran Foot is a self-taught C# developer with a deep passion for learning new technologies and techniques. He is constantly exploring the latest developments in C#, with a particular focus on web technologies. As the lead software developer at ConnX Business Solutions, a small software company based in the UK, he has the opportunity to apply his knowledge in practice and assist others in acquiring new skills. He enjoys helping others and is an active member of the Packt community.
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
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 code below to receive a free ebook of your choice.
https://packt.link/NzOWQ
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily.
Follow these simple steps to get the benefits:
Scan the QR code or visit the link below:https://packt.link/free-ebook/9781835881224
Submit your proof of purchase.That’s it! We’ll send your free PDF and other benefits to your email directly.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 contentsSetting up your development environmentUnderstanding .NETBuilding console apps using Visual StudioBuilding console apps using VS CodeMaking good use of the GitHub repository for this bookLooking for helpLet’s get started by introducing you to the code solutions, structure, and content of 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.
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.
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 [email protected], or raise an issue in the GitHub repository for the book at the following link: https://github.com/markjprice/cs13net9/issues.
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.
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.
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.
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.
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 WindowsVS Code for Windows, Mac, or LinuxVS Code for the Web or GitHub CodespacesThird 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
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 12to15, which are about web development, you will build websites and services using the modern parts of ASP.NET Core, including Blazor and Minimal APIs.
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 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 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/.
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.
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.
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:
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.
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.
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:
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.
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.
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.
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.
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.csdevkitI 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.
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 releaseVersion 1.93.1, August 2024 bug fix releaseThe 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.
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:
Windows: https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdfmacOS: https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdfLinux: https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf“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.
.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.
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.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.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
.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 --infoGood 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.
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.
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 technologiesVisual 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.
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
Let’s get started writing code:
Start Visual Studio.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.
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.
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.
Figure 1.4: Editing Program.cs in Visual Studio
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.
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.
The next task is to compile and run the code:
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.
Figure 1.5: Running the console app on Windows
Press any key to close the console app window and return to Visual Studio.Optionally, close the Properties pane to make more vertical space for Solution Explorer.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.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
Two compiler-generated folders were created, named obj and bin, as described in the following list:
The obj folder contains