C# 9 and .NET 5 – Modern Cross-Platform Development Fifth Edition Build intelligent apps, websites, and services with Blazor, ASP.NET Core, and Entity Framework Core using Visual Studio Code Mark J. Price BIRMINGHAM - MUMBAI C# 9 and .NET 5 – Modern Cross-Platform Development Fifth Edition Copyright © 2020 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. Producer: Ben Renow-Clarke Acquisition Editor – Peer Reviews: Divya Mudaliar Content Development Editors: Joanne Lovell, Bhavesh Amin Technical Editor: Aniket Shetty Project Editor: Radhika Atitkar Copy Editor: Safis Editing Proofreader: Safis Editing Indexer: Rekha Nair Presentation Designer: Sandip Tadge First published: March 2016 Second edition: March 2017 Third edition: November 2017 Fourth edition: October 2019 Fifth edition: November 2020 Production reference: 1051120 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-80056-810-5 www.packt.com packt.com Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. Why subscribe? • Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals • Learn better with Skill Plans built especially for you • Get a free eBook or video every month • Fully searchable for easy access to vital information • Copy and paste, print, and bookmark content Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.Packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.Packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. Contributors About the author Mark J. Price is a Microsoft Specialist: Programming in C# and architecting Microsoft Azure Solutions, with more than 20 years of educational and programming experience. Since 1993, Mark has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them too. His students range from professionals with decades of experience to 16-year-old apprentices with none. He successfully guides all of them by combining educational skills with real-world experience in consulting and developing systems for enterprises worldwide. Between 2001 and 2003, Mark was employed full time to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught "train-the-trainer" classes to get other MCTs up to speed on C# and .NET. Currently, Mark creates and delivers training courses for Episerver's Digital Experience Platform, including Content Cloud, Commerce Cloud, and Intelligence Cloud. In 2010, Mark studied for a Postgraduate Certificate in Education (PGCE). He taught GCSE and A-Level mathematics in two London secondary schools. He holds a Computer Science BSc. Hons. degree from the University of Bristol, UK. Thank you to my parents, Pamela and Ian, for raising me to be polite, hardworking, and curious about the world. Thank you to my sisters, Emily and Juliet, for loving me despite being their awkward older brother. Thank you to my friends and colleagues who inspire me technically and creatively. Lastly, thanks to all the students I have taught over the years for motivating me to be the best teacher that I can be. About the reviewer Damir Arh has many years of experience with software development and maintenance; from complex enterprise software projects to modern consumer-oriented mobile applications. Although he has worked with a wide spectrum of different languages, his favorite language remains C#. In his drive toward better development processes he is a proponent of test-driven development, continuous integration, and continuous deployment. He shares his knowledge by speaking at local user groups and conferences, blogging, and writing articles. He has received the prestigious Microsoft MVP award for developer technologies 9 times in a row. In his spare time, he's always on the move: hiking, geocaching, running, and rock climbing. I'd like to thank my family and friends for their patience and understanding during the weekends and evenings I spent on my computer to help make this book better for everyone. Table of Contents Preface xxi Chapter 1: Hello, C#! Welcome, .NET! 1 Setting up your development environment 2 Using Visual Studio Code for cross-platform development 2 Using GitHub Codespaces for development in the cloud 3 Using Visual Studio 2019 for Windows app development 4 Using Visual Studio for Mac for mobile development 4 Recommended tools for chapters 4 Deploying cross-platform 5 Understanding Microsoft Visual Studio Code versions 5 Downloading and installing Visual Studio Code 7 Installing other extensions 8 Understanding .NET 8 Understanding .NET Framework 8 Understanding the Mono and Xamarin projects 9 Understanding .NET Core 9 Understanding .NET 5 and the journey to one .NET 10 Understanding .NET support 11 Understanding .NET Runtime and .NET SDK versions 12 Removing old versions of .NET 13 What is different about .NET Core and .NET 5? 14 Understanding .NET Standard 15 .NET platforms and tools used by the book editions 16 Understanding intermediate language 17 Comparing .NET technologies 17 Building console apps using Visual Studio Code 17 Writing code using Visual Studio Code 18 Compiling and running code using the dotnet CLI 20 Writing top-level programs 20 Downloading solution code from the GitHub repository 21 [ i ] Table of Contents Using Git with Visual Studio Code 21 Cloning the book solution code repository 22 Looking for help 22 Reading Microsoft documentation 22 Getting help for the dotnet tool 22 Getting definitions of types and their members 23 Looking for answers on Stack Overflow 25 Searching for answers using Google 26 Subscribing to the official .NET blog 26 Scott Hanselman's videos 26 Practicing and exploring 27 Exercise 1.1 – Test your knowledge 27 Exercise 1.2 – Practice C# anywhere 27 Exercise 1.3 – Explore topics 27 Summary 28 Chapter 2: Speaking C# 29 Introducing C# 29 Understanding language versions and features 30 C# 1.0 30 C# 2.0 30 C# 3.0 30 C# 4.0 31 C# 5.0 31 C# 6.0 31 C# 7.0 31 C# 7.1 32 C# 7.2 32 C# 7.3 32 C# 8.0 32 C# 9.0 33 Discovering your C# compiler versions 33 Enabling a specific language version compiler 35 Understanding C# basics 36 Understanding C# grammar 37 Statements 37 Comments 37 Blocks 38 Understanding C# vocabulary 38 Changing the color scheme for syntax 38 Comparing programming languages to human languages 39 Help for writing correct code 39 Verbs are methods 40 Nouns are types, fields, and variables 40 Revealing the extent of the C# vocabulary 41 Working with variables 43 Naming things and assigning values 44 Literal values 44 Storing text 44 [ ii ] Table of Contents Understanding verbatim strings 45 Storing numbers 46 Storing whole numbers 46 Storing real numbers 48 Writing code to explore number sizes 48 Comparing double and decimal types 49 Storing Booleans 51 Using Visual Studio Code workspaces 51 Storing any type of object 52 Storing dynamic types 53 Declaring local variables 54 Specifying and inferring the type of a local variable 54 Using target-typed new to instantiate objects 55 Getting default values for types 55 Storing multiple values 56 Working with null values 57 Making a value type nullable 57 Understanding nullable reference types 58 Enabling nullable and non-nullable reference types 59 Declaring non-nullable variables and parameters 59 Checking for null 61 Exploring console applications further 62 Displaying output to the user 62 Formatting using numbered positional arguments 62 Formatting using interpolated strings 63 Understanding format strings 63 Getting text input from the user 65 Importing a namespace 65 Simplifying the usage of the console 66 Getting key input from the user 66 Getting arguments 67 Setting options with arguments 69 Handling platforms that do not support an API 70 Practicing and exploring 71 Exercise 2.1 – Test your knowledge 71 Exercise 2.2 – Practice number sizes and ranges 71 Exercise 2.3 – Explore topics 72 Summary 72 Chapter 3: Controlling Flow and Converting Types 73 Operating on variables 73 Unary operators 74 Binary arithmetic operators 75 Assignment operators 76 Logical operators 76 Conditional logical operators 78 Bitwise and binary shift operators 79 [ iii ]