Reader small image

You're reading from  C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals - Eighth Edition

Product typeBook
Published inNov 2023
PublisherPackt
ISBN-139781837635870
Edition8th Edition
Right arrow
Author (1)
Mark J. Price
Mark J. Price
author image
Mark J. Price

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

Right arrow

Preface

There are programming books that are thousands of pages long that aim to be comprehensive references to the C# language, the .NET libraries, and app models like websites, services, and desktop and mobile apps.

This book is different. It is concise and aims to be a brisk, fun read that is packed with practical hands-on walk-throughs of each subject. The breadth of the overarching narrative comes at the cost of some depth, but you will find many signposts to explore further if you wish.

This book is simultaneously a step-by-step guide to learning modern C# and proven practices using cross-platform .NET, and a brief introduction to the fundamentals of web development, along with the creation of websites and services that can be built with these technologies. This book is most suitable for beginners to C# and .NET, as well as programmers who have worked with C# in the past but may feel left behind by the changes in the past few years.

If you already have experience with older versions of the C# language, then in the first topic of Chapter 2, Speaking C#, you can review the tables of new language features in an online section and jump straight to them.

If you already have experience with older versions of the .NET libraries, then in the first topic of Chapter 7, Packaging and Distributing .NET Types, you can review the tables of the new library features in an online section and jump straight to them.

I will point out the cool corners and gotchas of C# and .NET so that you can impress colleagues and get productive fast. Rather than slowing down and boring some readers by explaining every little thing, I will assume that you are smart enough to Google an explanation for topics that are related but not necessary to include in a beginner-to-intermediate guide that has limited space in a printed book.

Some chapters have links to additional related online-only content for those readers who would like more details. For example, Chapter 1, Hello, C#! Welcome, .NET!, has an online section about the history and background of .NET.

Where to find the code solutions

You can download solutions for the step-by-step guided tasks and exercises from the GitHub repository at the following link: https://github.com/markjprice/cs12dotnet8.

If you don’t know how to download or clone a GitHub repository, then I provide instructions at the end of Chapter 1, Hello, C#! Welcome, .NET!.

What this book covers

Chapter 1, Hello, C#! Welcome, .NET!, is about setting up your development environment to use either Visual Studio 2022 or Visual Studio Code with C# Dev Kit. Then you will learn how to use them to create the simplest application possible with C# and .NET. For simplified console apps, you will see the use of the top-level program feature introduced in C# 9, which is then used by default in the project templates for C# 10 onwards. You will also learn about some good places to look for help, including AI tools like ChatGPT and GitHub Copilot, and ways to contact me to get help with an issue or give me feedback to improve the book today through its GitHub repository and in future print editions.

Chapter 2, Speaking C#, introduces the versions of C# and has tables showing which version introduced new features in an online section. I will explain the grammar and vocabulary that you will use every day to write the source code for your applications. In particular, you will learn how to declare and work with variables of different types.

Chapter 3, Controlling Flow, Converting Types, and Handling Exceptions, covers using operators to perform simple actions on variables, including comparisons, writing code that makes decisions, pattern matching, repeating a block of statements, and converting between types. This chapter also covers writing code defensively to handle exceptions when they inevitably occur, including using guard clauses like ThrowIfLessThan on the ArgumentOutOfRangeException class introduced with .NET 8.

Chapter 4, Writing, Debugging, and Testing Functions, is about following the Don’t Repeat Yourself (DRY) principle by writing reusable functions using both imperative and functional implementation styles. You will also learn how to use debugging tools to track down and remove bugs, use Hot Reload to make changes while your app is running, monitor your code while it executes to diagnose problems, and rigorously test your code to remove bugs, ensuring stability and reliability before it gets deployed into production.

Chapter 5, Building Your Own Types with Object-Oriented Programming, discusses all the different categories of members that a type like a class can have, including fields to store data and methods to perform actions. You will use Object-Oriented Programming (OOP) concepts, such as aggregation and encapsulation, and how to manage namespaces for types, including the ability to alias any type introduced with C# 12. You will learn language features such as tuple syntax support and out variables, local functions, and default literals and inferred tuple names. You will also learn how to define and work with immutable types using the record keyword, init-only properties, and with expressions, introduced in C# 9. Finally, we look at how C# 11 introduced the required keyword to help avoid the overuse of constructors to control initialization, and how C# 12 introduced primary constructors for non-record types.

Chapter 6, Implementing Interfaces and Inheriting Classes, explains deriving new types from existing ones using OOP. You will learn how to define operators, delegates, and events, how to implement interfaces about base and derived classes, how to override a member of a type, how to use polymorphism, how to create extension methods, how to cast between classes in an inheritance hierarchy, and about the big changes in C# 8 with the introduction of nullable reference types, along with the switch to make this the default in C# 10 and later. In an optional online-only section, you can learn how analyzers can help you write better code.

Chapter 7, Packaging and Distributing .NET Types, introduces the versions of .NET and includes tables showing which version introduced new library features in an online section. I will then present the .NET types that are compliant with .NET Standard and explain how they relate to C#. Throughout this chapter, you will learn how to write and compile code on any of the supported operating systems, including the Windows, macOS, and Linux variants. You will learn how to package, deploy, and distribute your own apps and libraries. In two optional online-only sections, you can learn how to use legacy .NET Framework libraries in .NET libraries, about the possibility of porting legacy .NET Framework code bases to modern .NET, and about source generators and how to create them.

Chapter 8, Working with Common .NET Types, discusses the types that allow your code to perform common practical tasks, such as manipulating numbers and text, storing items in collections, and, in an optional online-only section, working with a network using low-level types. You will also learn about regular expressions and the improvements that make writing them easier, as well as how to use source generators to improve their performance.

Chapter 9, Working with Files, Streams, and Serialization, covers interacting with a filesystem, reading and writing to files and streams, text encoding, and serialization formats like JSON and XML, including the improved functionality and performance of the System.Text.Json classes. If you use Linux, then you will be interested in how to programmatically work with tar archives, which you can learn about in an online-only section.

Chapter 10, Working with Data Using Entity Framework Core, explains reading and writing to relational databases, such as SQL Server and SQLite, using the object-relational mapping (ORM) technology named Entity Framework Core (EF Core). You will learn how to define entity models that map to existing tables in a database using Database First models. In two optional online-only sections, you can also learn how to define Code First models that can create tables and databases at runtime, and how to group multiple changes together using transactions.

Chapter 11, Querying and Manipulating Data Using LINQ, teaches you about Language INtegrated Queries (LINQ)—language extensions that add the ability to work with sequences of items and filter, sort, and project them into different outputs. This chapter includes LINQ methods introduced in .NET 6, like TryGetNonEnumeratedCount and DistinctBy, and in .NET 7, like Order and OrderDescending. Optional online-only sections cover using multiple threads with parallel LINQ, working with LINQ to XML, and creating your own LINQ extension methods.

Chapter 12, Introducing Web Development Using ASP.NET Core, introduces you to the types of web applications that can be built using C# and .NET. You will also build an EF Core model to represent the database for a fictional organization named Northwind that will be used throughout the rest of the chapters in the book. Finally, you will be introduced to common web technologies.

Chapter 13, Building Websites Using ASP.NET Core Razor Pages, is about learning the basics of building websites with a modern HTTP architecture on the server side, using ASP.NET Core. You will learn how to implement the ASP.NET Core feature known as Razor Pages, which simplifies creating dynamic web pages for small websites. Additionally, the chapter covers building the HTTP request and response pipeline. In two optional online-only sections, you’ll see how to use Razor class libraries to reuse Razor Pages, and you’ll gain insight into enabling HTTP/3 in your website project.

Online Chapter, Building Websites Using the Model-View-Controller Pattern, is about learning how to build large, complex websites in a way that is easy to unit-test and manage with teams of programmers, using ASP.NET Core MVC. You will learn about startup configuration, authentication, routes, models, views, and controllers. You will learn about a feature eagerly anticipated by the .NET community called output caching that was finally implemented in ASP.NET Core 7. You can read this at https://packt.link/WKg6b

Chapter 14, Building and Consuming Web Services, explains building backend REST architecture web services using the ASP.NET Core Web API. We will cover how to document and test them using OpenAPI. Then we will see how to properly consume them using factory-instantiated HTTP clients. In two optional online-only sections, you will be introduced to advanced features like health checks, adding security HTTP headers, and minimal APIs, and how they can use native ahead-of-time (AOT) compilation during the publishing process to improve startup time and memory footprint.

Chapter 15, Building User Interfaces Using Blazor, introduces how to build web user interface components using Blazor that can be executed either on the server side or inside the web browser. You will see how to build components that are easy to switch between the client and the server, with the new hosting model introduced with .NET 8.

Epilogue describes your options for further study about C# and .NET.

Appendix, Answers to the Test Your Knowledge Questions, has the answers to the test questions at the end of each chapter. You can read the appendix at the following link: https://packt.link/NTPzz.

What you need for this book

You can develop and deploy C# and .NET apps using Visual Studio Code and the command-line tools on most operating systems, including Windows, macOS, and many varieties of Linux. An operating system that supports Visual Studio Code and an internet connection is all you need to follow along with this book.

If you prefer alternatives, then the choice is yours whether to use Visual Studio 2022, or a third-party tool like JetBrains Rider.

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots and diagrams used in this book. The color images will help you better understand the changes in the output.

You can download this file from https://packt.link/gbp/9781837635870.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: “The Controllers, Models, and Views folders contain ASP.NET Core classes and the .cshtml files for execution on the server.”

A block of code is set as follows:

// storing items at index positions 
names[0] = "Kate";
names[1] = "Jack"; 
names[2] = "Rebecca"; 
names[3] = "Tom";

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are highlighted:

// storing items at index positions 
names[0] = "Kate";
names[1] = "Jack"; 
names[2] = "Rebecca"; 
names[3] = "Tom";

Any command-line input or output is written as follows:

dotnet new console

Bold: Indicates a new term, an important word, or words that you see on the screen, for example, in menus or dialog boxes. For example: “Clicking on the Next button moves you to the next screen.”

Important notes and links to external sources for further reading appear in a box like this.

Good Practice: Recommendations for how to program like an expert appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at customercare@packtpub.com.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, select your book, click on the Errata Submission Form link, and enter the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name.

Please contact us at copyright@packt.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

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:

  1. Scan the QR code or visit the link below:
Qr code

Description automatically generated

https://packt.link/free-ebook/9781837635870

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

lock icon
The rest of the chapter is locked
You have been reading a chapter from
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals - Eighth Edition
Published in: Nov 2023Publisher: PacktISBN-13: 9781837635870
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime

Author (1)

author image
Mark J. Price

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