C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals - Mark J. Price - E-Book

C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals E-Book

Mark J. Price

0,0
43,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

This latest edition of the bestselling Packt series will give you a solid foundation to start building projects using modern C# and .NET with confidence.

You'll learn about object-oriented programming; writing, testing, and debugging functions; and implementing interfaces. You'll take on .NET APIs for managing and querying data, working with the fi lesystem, and serialization. As you progress, you'll explore examples of cross-platform projects you can build and deploy, such as websites and services using ASP.NET Core.

This latest edition integrates .NET 8 enhancements into its examples: type aliasing and primary constructors for concise and expressive code. You'll handle errors robustly through the new built-in guard clauses and explore a simplified implementation of caching in ASP.NET Core 8.

If that's not enough, you'll also see how native ahead-of-time (AOT) compiler publish lets web services reduce memory use and run faster. You'll work with the seamless new HTTP editor in Visual Studio 2022 to enhance the testing and debugging process. You'll even get introduced to Blazor Full Stack with its new unified hosting model for unparalleled web development flexibility.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 1114

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals

Eighth Edition

Start building websites and services with ASP.NET Core 8, Blazor, and EF Core 8

Mark J. Price

BIRMINGHAM—MUMBAI

C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals

Eighth Edition

Copyright © 2023 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: Tejas Mhasvekar

Project Editor: Janice Gonsalves

Content Development Editor: Shazeen Iqbal

Copy Editor: Safis Editing

Technical Editor: Karan Sonawane

Proofreader: Safis Editing

Indexer: Tejal Soni

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

Production reference: 2171123

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN 978-1-83763-587-0

www.packt.com

Contributors

About the author

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 Computer Science BSc. Hons. Degree.

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, 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 Troy, a reader who became a colleague and more importantly, a good friend.

About the reviewer

Troy Martin is a self-taught developer of over 10 years, focusing mainly on C# the last several of those years. Deeply passionate about programming, he has over 20 certifications in various languages and game development engines. He is currently engaged in developing his first solo game development project and strives to help others achieve their own programming goals.

I’d like to thank my wonderful girlfriend, Haley, who has stood by me even through the worst of times; I love you, Penne!

Also, my deepest thanks to Mark Price, the author himself, who has been a wonderful and incredibly informative friend throughout this process.

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

Contents

Preface

Where to find the code solutions

What this book covers

What you need for this book

Get in touch

Hello, C#! Welcome, .NET!

Introducing this book and its contents

Setting up your development environment

Understanding .NET

Building console apps using Visual Studio 2022

Building console apps using Visual Studio Code

Making good use of the GitHub repository for this book

Looking for help

Practicing and exploring

Summary

Learn more on Discord

Speaking C#

Introducing the C# language

Discovering your C# compiler version

Understanding C# grammar and vocabulary

Working with variables

Exploring more about console apps

Understanding async and await

Practicing and exploring

Summary

Controlling Flow, Converting Types, and Handling Exceptions

Operating on variables

Understanding selection statements

Understanding iteration statements

Storing multiple values in an array

Casting and converting between types

Handling exceptions

Checking for overflow

Practicing and exploring

Summary

Writing, Debugging, and Testing Functions

Writing functions

Debugging during development

Hot reloading during development

Logging during development and runtime

Unit testing

Throwing and catching exceptions in functions

Practicing and exploring

Summary

Building Your Own Types with Object-Oriented Programming

Talking about OOP

Building class libraries

Storing data in fields

Working with methods and tuples

Controlling access with properties and indexers

Pattern matching with objects

Working with record types

Practicing and exploring

Summary

Implementing Interfaces and Inheriting Classes

Setting up a class library and console application

Static methods and overloading operators

Making types safely reusable with generics

Raising and handling events

Implementing interfaces

Managing memory with reference and value types

Working with null values

Inheriting from classes

Casting within inheritance hierarchies

Inheriting and extending .NET types

Summarizing custom type choices

Practicing and exploring

Summary

Packaging and Distributing .NET Types

The road to .NET 8

Understanding .NET components

Publishing your code for deployment

Native ahead-of-time compilation

Decompiling .NET assemblies

Packaging your libraries for NuGet distribution

Working with preview features

Practicing and exploring

Summary

Working with Common .NET Types

Working with numbers

Working with text

Pattern matching with regular expressions

Storing multiple objects in collections

Working with spans, indexes, and ranges

Practicing and exploring

Summary

Working with Files, Streams, and Serialization

Managing the filesystem

Reading and writing with streams

Encoding and decoding text

Serializing object graphs

Working with environment variables

Practicing and exploring

Summary

Working with Data Using Entity Framework Core

Understanding modern databases

Setting up EF Core in a .NET project

Defining EF Core models

Querying EF Core models

Loading and tracking patterns with EF Core

Modifying data with EF Core

Practicing and exploring

Summary

Querying and Manipulating Data Using LINQ

Writing LINQ expressions

LINQ in practice

Sorting and more

Using LINQ with EF Core

Joining, grouping, and lookups

Aggregating and paging sequences

Practicing and exploring

Summary

Introducing Web Development Using ASP.NET Core

Understanding ASP.NET Core

Structuring projects

Building an entity model for use in the rest of the book

Understanding web development

Practicing and exploring

Summary

Building Websites Using ASP.NET Core Razor Pages

Exploring ASP.NET Core

Exploring ASP.NET Core Razor Pages

Using Entity Framework Core with ASP.NET Core

Configuring services and the HTTP request pipeline

Practicing and exploring

Summary

Building and Consuming Web Services

Building web services using the ASP.NET Core Web API

Creating a web service for the Northwind database

Documenting and testing web services

Consuming web services using HTTP clients

Practicing and exploring

Summary

Building User Interfaces Using Blazor

History of Blazor

Reviewing the Blazor Web App project template

Building components using Blazor

Enabling client-side execution using WebAssembly

Practicing and exploring

Summary

Epilogue

Next steps on your C# and .NET learning journey

The ninth edition, coming November 2024

Good luck!

Index

Landmarks

Cover

Index

Share your thoughts

Once you’ve read C# 12 and .NET 8 - Modern Cross-Platform Development Fundamentals, Eighth Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

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

Submit your proof of purchase.That’s it! We’ll send your free PDF and other benefits to your email directly.

1

Hello, C#! Welcome, .NET!

In this first chapter, the goals are setting up your development environment; understanding the similarities and differences between modern .NET, .NET Core, .NET Framework, Mono, Xamarin, and .NET Standard; creating the simplest application possible with C# 12 and .NET 8 using various code editors; and then discovering good places to look for help.

This chapter covers the following topics:

Introducing this book and its contentsSetting up your development environmentUnderstanding .NETBuilding console apps using Visual Studio 2022Building console apps using Visual Studio CodeMaking good use of the GitHub repository for this bookLooking for help

Introducing this book and its contents

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

Getting code solutions for this book

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

https://github.com/markjprice/cs12dotnet8

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 Visual Studio Code using GitHub Codespaces, as shown in Figure 1.1:

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

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.

Visual Studio 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/cs12dotnet8/archive/refs/heads/main.zip.

.NET terms used in this book

Throughout this book, I use the term modern .NET to refer to .NET 8 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 can be divided into three parts: language, libraries, and web development.

First, the grammar and vocabulary of the C# language; second, the types available in the .NET libraries for building app features; and third, 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/csharp12dotnet8, email me at [email protected], or raise an issue in the GitHub repository for the book at the following link: https://github.com/markjprice/cs12dotnet8/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.Web development fundamentals: Fundamental features of the ASP.NET Core framework for server-side and client-side website and web service development.

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, 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, C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals, is best read linearly, chapter by chapter, because it builds up fundamental skills and knowledge.

The companion book, Apps and Services with .NET 8, can be read more like a cookbook, so if you are especially interested in building gRPC services, then you could read that chapter without the preceding chapters about minimal API services.

To see a list of all 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#. Microsoft has a family of code editors and Integrated Development Environments (IDEs), which include:

Visual Studio 2022 for WindowsVisual Studio Code for Windows, Mac, or LinuxVisual Studio Code for the Web or GitHub Codespaces

Third parties have created their own C# code editors, for example, JetBrains Rider, which is available for Windows, Mac, or Linux but does have a license cost. JetBrains 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 so the warning does not apply.

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 can 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 Visual Studio Code, Visual Studio 2022, or even JetBrains Rider.

In this book, I give detailed step-by-step instructions in Chapter 1 for how to create multiple projects in both Visual Studio 2022 for Windows and Visual Studio Code. There are also links to online instructions for other code editors, as shown at the following link: https://github.com/markjprice/cs12dotnet8/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 12to16, you will build websites, services, and web browser apps.

Pros and cons of the Polyglot Notebooks extension

The Polyglot Notebooks extension for Visual Studio Code provides an easy and safe place to write simple code snippets for experimenting and learning. For example, data scientists use them to analyze and visualize data. Students use them to learn how to write small pieces of code for language constructs and to explore APIs.

Polyglot Notebooks enables you to create a single notebook file that mixes “cells” of Markdown (richly formatted text) and code using C# and other related languages, such as PowerShell, F#, and SQL (for databases). The extension does this by hosting an instance of the .NET Interactive engine.

The old legacy name for the Polyglot Notebooks extension was the .NET InteractiveNotebooks extension but it was renamed because it is not limited to only .NET languages like C# and F#. The extension retains its original identifier, ms-dotnettools.dotnet-interactive-vscode.

Polyglot Notebooks has some limitations:

It cannot be used to create websites, services, and apps.You cannot use Console class methods like ReadLine or ReadKey to get input from the user. (But there are alternative methods that you will learn if you complete the optional online-only exercise at the end of this chapter.)Notebooks cannot have arguments passed to them.It does not allow you to define your own namespaces.It does not have any debugging tools (yet).

At the end of this chapter, you will have the opportunity to complete an optional exercise to practice using Polyglot Notebooks.

Visual Studio 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 Visual Studio 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.

Visual Studio Code is a good choice for modern cross-platform development because it has an extensive and growing set of extensions to support many languages beyond C#. The most important extension for C# and .NET developers is the C# Dev Kit that was released in preview in June 2023 because it turns Visual Studio 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, Visual Studio 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 Visual Studio Code means a developer can use a cross-platform code editor to develop cross-platform apps. Visual Studio Code is supported on ARM processors so that you can develop on Apple Silicon computers and Raspberry Pi computers.

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

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

GitHub Codespaces for development in the cloud

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

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

Visual Studio 2022 for general development

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

It 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 2022 for Mac does not officially support .NET 8 and it will reach end-of-life in August 2024. If you have been using Visual Studio 2022 for Mac then you should switch to Visual Studio Code for Mac, JetBrains Rider for Mac, or use Visual Studio 2022 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:

Visual Studio 2022 for Windows on:Windows 11 on an HP Spectre (Intel) laptopVisual Studio Code on:macOS on an Apple Silicon Mac mini (M1) desktopWindows 11 on an HP Spectre (Intel) laptopJetBrains Rider on:macOS on an Apple Silicon Mac mini (M1) desktopWindows 11 on an HP Spectre (Intel) laptop

I hope that you have access to a variety of hardware and software too, because 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.

You can learn how to write code with C# and .NET using a Raspberry Pi 400 with Ubuntu Desktop 64-bit by reading an extra article that I wrote at the following link: https://github.com/markjprice/cs12dotnet8/tree/main/docs/raspberry-pi-ubuntu64.

Deploying cross-platform

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

.NET 8 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. Nano Server version 1809 or later.Mac: macOS Catalina version 10.15 or later and in the Rosetta 2 x64 emulator.Linux: Alpine Linux 3.17 or later. Debian 11 or later. Fedora 37 or later. openSUSE 15 or later. Oracle Linux 8 or later. RHEL 8 or later. SUSE Enterprise Linux 12 SP2 or later. Ubuntu 20.04 or later.Android: API 21 or later.iOS and tvOS: 11.0 or later.Mac Catalyst: 10.15 or later. 11.0 or later on ARM64.

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

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

Downloading and installing Visual Studio 2022

Many professional .NET developers use Visual Studio 2022 for Windows in their day-to-day development work. Even if you choose to use Visual Studio Code to complete the coding tasks in this book, you might want to familiarize yourself with Visual Studio 2022 for Windows 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 Visual Studio 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 Microsoft Visual Studio 2022 version 17.8 or later for Windows from the following link: https://visualstudio.microsoft.com/downloads/.Run the installer to start the installation.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 publishing console apps and web services that start faster and have smaller memory footprints).Click Install and wait for the installer to acquire the selected software and install it.When the installation is complete, click Launch.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/.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.If you want to customize your keyboard shortcuts, navigate to Tools | Options…, and then select the Keyboard section.

Keyboard shortcuts for Visual Studio 2022 for Windows

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 Visual Studio Code

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

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

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

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

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

Download and install the .NET SDK for version 8.0 and at least one other version like 6.0 or 7.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 6, .NET 7, and .NET 8 are supported versions at the time of publishing in November 2023. You can safely install multiple SDKs side by side. The most recent SDK will be used to build your projects.

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

Click Install and wait for 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 Visual Studio 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. Manage your code with a solution explorer and test your code with integrated unit test discovery and execution.

Includes the C# and IntelliCode for C# Dev Kit extensions.

C#

ms-dotnettools.csharp

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

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.

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 Visual Studio Code.

Table 1.1: Visual Studio Code extensions used in this book

Managing Visual Studio Code extensions at the command prompt

You can install a Visual Studio 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: Commands to list, install, and uninstall extensions

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 Visual Studio Code extensions in the preceding table. You can find them at the following link: https://github.com/markjprice/cs12dotnet8/tree/main/scripts/extension-scripts/.

Understanding Visual Studio Code versions

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

Version 1.79.0, May 2023 feature releaseVersion 1.79.1, May 2023 bug fix release

The version used in this book is 1.82.1, August 2023 bug fix release, but the version of Visual Studio Code is less important than the version of the C# Dev Kit or C# extension that you install. I recommend C# extension v2.8.23 or later and C# Dev Kit v0.5.150 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 Visual Studio Code

If you want to customize your keyboard shortcuts for Visual Studio 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 Visual Studio 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

Understanding .NET

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

– George Santayana

.NET, .NET Core, .NET Framework, 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 introduce you to each of these .NET concepts at the following link:

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

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 8.0.0 and then version 8.0.1 is released, you must install version 8.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 it visually, with 3-year-long black bars for LTS releases, and 1½-year-long gray bars for STS releases, as shown in Figure 1.2:

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

During the lifetime of .NET 8, two older versions will reach end-of-life and two new versions will be released. I have tried to be cognizant that you might choose to use .NET 9 or .NET 10 with this book; although, obviously, the book cannot cover new features of those future versions!

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.

If you need long-term support from Microsoft, then choose .NET 8 today and stick with it even after .NET 9 releases in 2024. This is because .NET 9 will be an STS release, and it will therefore 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 8.0.1 and .NET SDK 8.0.101, which are expected to release in December 2023, because updates are released every month.

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

.NET 7 will reach end-of-life on May 14, 2024..NET 6 will reach end-of-life on November 12, 2024..NET 8 will reach end-of-life on November 10, 2026.

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

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: Not supported. .NET 8 Preview 1 to Preview 7 were in this support phase from February 2023 to August 2023.Go Live: Supported until GA, then becomes immediately unsupported so you must upgrade to the final release version as soon as it is available. .NET 8 Release Candidate 1 and Release Candidate 2 were in this support phase in September and October 2023.Active: .NET 8 will be in this support phase from November 2023 to May 2026.Maintenance: Supported only with security fixes for the last 6 months of its lifetime. .NET 8 will be in this support phase from May 2026 to November 2026.End-of-life: Not supported. .NET 8 will reach its end of life in November 2026.

Understanding .NET runtime and .NET SDK versions

If you have not built a standalone app, then the .NET runtime is the minimum needed 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 it is matched with. The third number follows a convention that indicates the minor and patch versions of the SDK. The minor number is multiplied by 100 and added to the patch number.

You can see an example of this in Table 1.3:

Change

Runtime

SDK

Initial release

8.0.0

8.0.100

SDK bug fix

8.0.0

8.0.101

Runtime and SDK bug fix

8.0.1

8.0.102

SDK new feature

8.0.1

8.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 8.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 as a single statement that can be easily copied and pasted: https://github.com/markjprice/cs12dotnet8/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.

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 Common language runtimes (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.

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# 12 language support. It can be used to port existing apps or create new desktop, mobile, and web apps and services. It can target older .NET platforms.

Windows, macOS, Linux, Android, iOS, tvOS, 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, macOS

Table 1.4: Comparison of .NET technologies

Managing multiple projects using code editors

Visual Studio 2022 for Windows, JetBrains Rider, and even Visual Studio 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 2022

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

If you do not have a Windows computer or want to use Visual Studio Code, then you can skip this section since the code will be the same; just the tooling experience is different. But 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/cs12dotnet8/blob/main/docs/code-editors/vs4win.md

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

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

Writing code using Visual Studio 2022

Let’s get started writing code:

Start Visual Studio 2022. You might see an experimental new Welcome tab that replaces the old model dialog box, as shown in Figure 1.3.In the Welcome tab, click New Project, or if you are using a version with the Visual Studio 2022 modal dialog box, then in the Get started section, click Create a new project:

Figure 1.3: Welcome tab with buttons like New Project

In the Create a new project dialog, select the C# language to filter the project templates, and then enter console in the Search for templates box, and select Console App, making 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, so that it is selected as shown in Figure 1.4:

Figure 1.4: Selecting the C# Console App project template for modern cross-platform .NET

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

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

Click Next.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 8.0 (Long 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.

Leave the check box labeled Do not use top-level statements cleared. (Later in this chapter, you will create a console app that selects this option so you can see the difference.)Leave the check box labeled Enable native AOT publish cleared. You will learn what this option does in Chapter 7, Packaging and Distributing .NET Types.Click Create.If you cannot see Solution Explorer, then navigate to View | Solution Explorer.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.5:

Figure 1.5: Editing Program.cs in Visual Studio 2022

In Program.cs, note 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.

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 the reader 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.5, 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:

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

Good Practice