C# 7.1 and .NET Core 2.0 - Modern Cross-Platform Development - Third Edition

4.7 (30 reviews total)
By Mark J. Price
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Hello, C#! Welcome, .NET Core!

About this book

C# 7.1 and .NET Core 2.0 - Modern Cross-Platform Development (Third Edition) is a practical guide to creating powerful cross-platform applications with C# 7.1 and .NET Core 2.0. It gives readers of any experience level a solid foundation in C# and .NET. The first part of the book runs you through the basics of C#, as well as debugging functions and object-oriented programming, before taking a quick tour through the latest features of C# 7.1 such as default literals, tuples, inferred tuple names, pattern matching, out variables, and more.

After quickly taking you through C# and how .NET works, this book dives into the .NET Standard 2.0 class libraries, covering topics such as packaging and deploying your own libraries, and using common libraries for working with collections, performance, monitoring, serialization, files, databases, and encryption. The final section of the book demonstrates the major types of application that you can build and deploy cross-device and cross-platform. In this section, you'll learn about websites, web applications, web services, Universal Windows Platform (UWP) apps, and mobile apps. By the end of the book, you'll be armed with all the knowledge you need to build modern, cross-platform applications using C# and .NET.

Publication date:
November 2017
Publisher
Packt
Pages
800
ISBN
9781788398077

 

Chapter 1. Hello, C#! Welcome, .NET Core!

This chapter is about setting up your development environment, understanding the similarities and differences between .NET Core, .NET Framework, .NET Standard, and .NET Native, and using various tools to create the simplest application possible with C# and .NET Core.

Most people learn complex topics by imitation and repetition rather than reading a detailed explanation of theory. So, I will not explain every keyword and step. The idea is to get you to write some code, build an application, and see it run. You don't need to know the details of how it all works yet.

In the words of Samuel Johnson, author of the English dictionary in 1755, I have likely 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 .NET Core and its command-line tooling during its rocky birth during 2016 and 2017.

This chapter covers the following topics:

  • Setting up your development environment
  • Understanding .NET
  • Writing and compiling code using the .NET Core CLI tool
  • Writing and compiling code using Visual Studio 2017
  • Writing and compiling code using Visual Studio Code
  • Writing and compiling code using Visual Studio for Mac
  • Managing source code with GitHub
 

Setting up your development environment


Before you start programming, you will need to choose an Integrated Development Environment (IDE) that includes a code editor for C#. Microsoft has a family of IDEs:

  • Visual Studio 2017
  • Visual Studio for Mac
  • Visual Studio Code

The most mature and fully-featured IDE to choose is Microsoft Visual Studio 2017, but it only runs on the Windows operating system.

The most modern and lightweight IDE to choose, and the only one from Microsoft that is cross-platform, is Microsoft Visual Studio Code, and it will run on all common operating systems, including Windows, macOS, and many varieties of Linux, such as Red Hat Enterprise Linux (RHEL) and Ubuntu.

Note

To help you decide if Visual Studio Code is right for you, I recommend that you watch the following video, Beginner's Guide to VS Code: Up and Running in Ten Minutes:https://channel9.msdn.com/Blogs/raw-tech/Beginners-Guide-to-VS-Code

The most suitable IDE to choose for mobile development is Visual Studio for Mac. To create apps for iOS (iPhone and iPad), tvOS, macOS, and watchOS, you must have macOS and Xcode. Although you can use Visual Studio 2017 with its Xamarin extensions to write a cross-platform mobile app, you still need macOS and Xcode to compile it.

The following table shows which IDE and operating systems can or must be used for each of the chapters in this book:

Chapters

IDE

Operating systems

Chapters 1 to 16

Visual Studio 2017

Windows 7 SP1 or later

Chapters 1 to 16

Visual Studio Code

Windows, macOS, Linux

Chapters 1 to 16

Visual Studio for Mac

macOS

Chapter 17

Visual Studio 2017

Windows 10

Chapter 18

Visual Studio for Mac

macOS

Note

Good Practice If you have the option, then I recommend that you try all the coding exercises with Visual Studio 2017 on Windows, Visual Studio Code on macOS, Linux, or Windows, and Visual Studio for Mac. It will be good for you to get experience with C# and .NET Core on a variety of operating systems and development tools.

To write the third edition of this book, I used the following listed software, as shown in the following screenshot:

  • Visual Studio 2017 on Windows 10 in a virtual machine
  • Visual Studio for Mac on macOS
  • Visual Studio Code on macOS
  • Visual Studio Code on RHEL (not shown in screenshot)

Using alternative C# IDEs

There are alternative IDEs for C#, for example, MonoDevelop and JetBrains Rider. You can install either of these two IDEs with the help of the following URLs:

Cloud9 is a web browser-based IDE, so it's even more cross-platform than the others. It is growing in popularity. Here is the link: https://c9.io/web/sign-up/free

Deploying cross-platform

Your choice of IDE and operating system for development does not limit where your code gets deployed. .NET Core 2.0 supports the following platforms for deployment:

  • Windows 7 SP1, or later
  • Windows Server 2008 R2 SP1, or later
  • Windows IoT 10, or later
  • macOS Sierra (version 10.12), or later
  • RHEL 7.3, or later
  • Ubuntu 14.04, or later
  • Fedora 25, or later
  • Debian 8.7, or later
  • openSUSE 42.2, or later
  • Tizen 4, or later

Note

Linux OSes are popular server host platforms because they are relatively lightweight and more cost-effectively scalable when compared to operating system platforms such as Windows and macOS.

In the next section, you will install Microsoft Visual Studio 2017 for Windows. If you prefer to use Microsoft Visual Studio Code, jump ahead to the Installing Microsoft Visual Studio Code for Windows, macOS, or Linux section. If you prefer to use Microsoft Visual Studio for Mac, jump ahead to the Installing Microsoft Visual Studio for Mac section.

Installing Microsoft Visual Studio 2017

You can use Windows 7 SP1 or later to complete most of the chapters in this book, but you will have a better experience if you use Windows 10 Fall Creators Update.

Since October 2014, Microsoft has made a professional-quality edition of Visual Studio available to everyone for free. It is called Community Edition.

Download and install Microsoft Visual Studio 2017 version 15.4 or later from the following link:

https://www.visualstudio.com/downloads/

Note

You must install version 15.4 or later of Visual Studio 2017 to be able to work with .NET Core for UWP. You must install version 15.3 or later of Visual Studio 2017 to be able to work with .NET Core 2.0. Older versions of Visual Studio 2017 only support .NET Core 1.0 and 1.1.

Choosing workloads

On the Workloads tab, choose the following, as partially shown in the following screenshot:

  • Universal Windows Platform development
  • .NET desktop development
  • ASP.NET and web development
  • Azure development
  • Node.js development
  • .NET Core cross-platform development

Choosing additional components

On the Individual components tab, choose the following additional components:

  • Class Designer
  • GitHub extension for Visual Studio
  • PowerShell tools

Click on Install, and wait for the installer to acquire the selected software, and install it. When the installation is complete, click on Launch.

Note

While you wait for Visual Studio 2017 to install, you can jump ahead to the Understanding .NET section in this chapter.

The first time that you run Visual Studio 2017, 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/

When starting Visual Studio 2017 for the first time, 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.

You will see the Microsoft Visual Studio user interface with the Start Page open in the central area. Like most Windows desktop applications, Visual Studio has a menu bar, a toolbar for common commands, and a status bar at the bottom. On the right is the Solution Explorer that will list your open projects:

Note

To have quick access to Visual Studio in the future, right-click on its entry in the Windows taskbar and select Pin this program to taskbar.

In Chapter 14, Building Web Sites Using ASP.NET Core Razor Pages, Chapter 15, Building Web Sites Using ASP.NET Core MVC, and Chapter 16, Building Web Services and Applications Using ASP.NET Core, you will need Node.js and NPM installed.

Download the Node.js installer for Windows from the following link:

https://nodejs.org/en/download/

Run the Node.js installer, as shown in the following screenshot:

Installing Microsoft Visual Studio Code

Between June 2015 and September 2017, Microsoft released a new version of Visual Studio Code almost every month. Visual Studio Code has rapidly improved and surprised Microsoft with its popularity. Even if you plan to use Visual Studio 2017 or Visual Studio for Mac as your primary development tool, I recommend that you learn how to use Visual Studio Code and the .NET Core command-line tool as well.

You can download Visual Studio Code from the following link:

https://code.visualstudio.com/

Note

You can read about Microsoft's plans for Visual Studio Code in 2018 at the following link:https://github.com/Microsoft/vscode/wiki/Roadmap

Installing Microsoft Visual Studio Code for macOS

In this book, I will show examples and screenshots of Visual Studio Code using the version for macOS. The steps for doing the same with Visual Studio Code for Windows and variants of Linux is very similar, so I will not repeat the instructions for every platform.

After downloading Visual Studio Code for macOS, drag and drop it to your Applications folder, as shown in the following screenshot:

You will now need to install the .NET Core SDK for macOS. The full instructions, including a video to watch, are described at the following link, and I have included the basic steps in this book for your convenience: https://www.microsoft.com/net/core#macos

The first step is to install Homebrew (if you don't already have it).

Start macOS's Terminal app and enter the following command at the prompt:

/usr/bin/ruby -e "$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/install/master/install)"

Terminal will prompt you to press Enter to continue and then prompt for your password.

Note

If you are using .NET Core 1.0 or 1.1, then at this point you will need to use Homebrew to install OpenSSL, which is a dependency of older versions of .NET Core on macOS.

Installing .NET Core SDK for macOS

The next step is to download the .NET Core SDK installer for macOS (x64) from the following link:

https://www.microsoft.com/net/download/core

Run the dotnet-sdk-2.0.0-sdk-osx-x64.pkg installer package, as shown in the following screenshot:

Click on Continue, accept the license agreement, click on Install, and then, once it has finished, click on Close.

Installing Node Package Manager for macOS

In Chapter 14, Building Web Sites Using ASP.NET Core Razor Pages, Chapter 15, Building Web Sites Using ASP.NET Core MVC, and Chapter 16, Building Web Services and Applications Using ASP.NET Core, you will need Node.js and NPM installed.

In Terminal, enter commands to install Node.js and NPM, and then check their versions, which at the time I wrote this book, were Node.js version 8.4 and NPM version 5.3, as shown in the following screenshot:

brew install node
node -v
npm -v

Installing the Visual Studio Code extension for C#

The C# for Visual Studio Code extension is not necessary, but it provides IntelliSense as you type, so it's very handy to install.

Launch Visual Studio Code and click on the Extensions icon, or go to View | Extensions, or press Cmd + Shift + X.

C# is the most popular extension, so you should see it at the top of the list, as shown in the following screenshot:

Click on Install, and then click on Reload, to reload the window and activate the extension.

Installing Visual Studio for Mac

In November 2016, Microsoft released a preview version of Visual Studio for Mac. Initially, it could only be used to create Xamarin mobile apps, because it is a fork of the Xamarin Studio product. The final release version, available since May 2017, has support for creating .NET Standard 2.0 class libraries, ASP.NET Core web applications and services, and console apps, so it can be used to complete (almost) all of the exercises in this book.

Although Visual Studio 2017 on Windows can be used to create mobile apps for iOS and Android, only Xcode running on macOS or OS X can compile iOS apps, so it is my opinion that a developer might as well use the native Visual Studio for Mac to create mobile apps.

Installing Xcode

If you have not already installed Xcode on your Mac, install it now from the App Store.

On the Apple menu, choose App Store....

In the App Store, enter xcode in the Search box, and one of the first results will be Xcode, as shown in the following screenshot:

Click on Get, and wait for Xcode to install.

Downloading and installing Visual Studio for Mac

You can download and install Visual Studio for Mac from the following link:

https://www.visualstudio.com/vs/visual-studio-mac/

In the Visual Studio for MacInstaller, accept the License Terms and the Privacy Statement, choose to install all components, and then click on Continue, as shown in the following screenshot:

Click on Continue, and then click on Install.

Agree to the license terms for the components, such as the Android SDK, click on Continue, and wait for Visual Studio for Mac to fully install.

Start Visual Studio for Mac to see the Welcome Page, as shown in the following screenshot:

If you are prompted to update components, then click on Restart and Install Updates.

Now that you have installed and set up your development environment, you will learn some background about .NET before diving in to writing code.

 

Understanding .NET


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

Understanding .NET Framework

Microsoft's .NET Framework is a development platform that includes a Common Language Runtime (CLR) that manages the execution of code, and provides a rich library of classes to build applications.

Microsoft designed .NET Framework to have the possibility of being cross-platform, but Microsoft put their implementation effort into making it work best with Windows.

Practically speaking, .NET Framework is Windows-only, and a legacy platform.

Understanding the Mono and Xamarin projects

Third parties developed a .NET implementation named the Mono project that you can read more about at the following link:http://www.mono-project.com/

Mono is cross-platform, but it fell well behind the official implementation of .NET Framework. It has found a niche as the foundation of the Xamarin mobile platform.

Microsoft purchased Xamarin in 2016 and now gives away what used to be an expensive Xamarin extension for free with Visual Studio 2017. Microsoft renamed the Xamarin Studio development tool to Visual Studio for Mac, and has given it the ability to create ASP.NET Core Web API services. Xamarin is targeted at mobile development and building cloud services to support mobile apps.

Understanding .NET Core

Today, we live in a truly cross-platform world. Modern mobile and cloud development has made Windows a much less important operating system. So, Microsoft has been working on an effort to decouple .NET from its close ties with Windows.

While rewriting .NET to be truly cross-platform, Microsoft has taken the opportunity to refactor .NET to remove major parts that are no longer considered core.

This new product is branded as .NET Core, which includes a cross-platform implementation of the CLR known as CoreCLR, and a streamlined library of classes known as CoreFX.

Scott Hunter, Microsoft Partner Director Program Manager for .NET, says, "Forty percent of our .NET Core customers are brand-new developers to the platform, which is what we want with .NET Core. We want to bring new people in."

The following table shows when important versions of .NET Core were released, and Microsoft's schedule for the next major release:

Version

Released

.NET Core RC1

November 2015

.NET Core 1.0

June 2016

.NET Core 1.1

November 2016

.NET Core 1.0.4 and .NET Core 1.1.1

March 2017

.NET Core 2.0

August 2017

.NET Core for UWP in Windows 10 Fall Creators Update

October 2017

.NET Core 2.1

Q1 2018

Note

If you need to work with .NET Core 1.0 and 1.1, then I recommend that you read the announcement for .NET Core 1.1, although the information at the following URL is useful for all .NET Core developers:https://blogs.msdn.microsoft.com/dotnet/2016/11/16/announcing-net-core-1-1/

.NET Core is much smaller than the current version of .NET Framework because a lot has been removed.

For example, Windows Forms and Windows Presentation Foundation (WPF) can be used to build graphical user interface (GUI) applications, but they are tightly bound to Windows, so they have been removed from .NET Core. The latest technology used to build Windows apps is Universal Windows Platform (UWP), and UWP is built on a custom version of .NET Core. You will learn about it in Chapter 17, Building Windows Apps Using XAML and Fluent Design.

ASP.NET Web Forms and Windows Communication Foundation (WCF) are old web application and service technologies that fewer developers choose to use for new development projects today, so they have also been removed from .NET Core. Instead, developers prefer to use ASP.NET MVC and ASP.NET Web API. These two technologies have been refactored and combined into a new product that runs on .NET Core, named ASP.NET Core. You will learn about ASP.NET Core MVC in Chapter 15, Building Web Sites Using ASP.NET Core MVC, ASP.NET Core Razor Pages in Chapter 14, Building Web Sites Using ASP.NET Core Razor Pages, and ASP.NET Core Web API and Single Page Applications (SPAs) such as Angular and React in Chapter 16, Building Web Services and Applications Using ASP.NET Core.

The Entity Framework (EF) 6 is an object-relational mapping technology to work with data stored in relational databases such as Oracle and Microsoft SQL Server. It has gained baggage over the years, so the cross-platform version has been slimmed down and named Entity Framework Core. You will learn about it in Chapter 11, Working with Databases Using Entity Framework Core.

In addition to removing large pieces from .NET Framework to make .NET Core, Microsoft has componentized .NET Core into NuGet packages: small chunks of functionality that can be deployed independently.

Note

Microsoft's primary goal is not to make .NET Core smaller than .NET Framework. The goal is to componentize .NET Core to support modern technologies and to have fewer dependencies, so that deployment requires only those packages that your application needs.

Understanding .NET Standard

The situation with .NET today is that there are three forked .NET platforms, all controlled by Microsoft:

  • .NET Framework
  • .NET Core
  • Xamarin

Each have different strengths and weaknesses because they are designed for different scenarios. This has led to the problem that a developer must learn three platforms, each with annoying quirks and limitations.

So, Microsoft defined .NET Standard 2.0: a specification for a set of APIs that all .NET platforms must implement. You cannot install .NET Standard 2.0 in the same way that you cannot install HTML5. To use HTML5, you must install a web browser that implements the HTML5 specification. To use .NET Standard 2.0, you must install a .NET platform that implements the .NET Standard 2.0 specification.

.NET Standard 2.0 is implemented by the latest versions of .NET Framework, .NET Core, and Xamarin. .NET Standard 2.0 makes it much easier for developers to share code between any flavor of .NET.

For .NET Core 2.0, this adds many of the missing APIs that developers need to port old code written for .NET Framework to the cross-platform .NET Core. However, some APIs are implemented, but throw an exception to indicate to a developer that they should not actually be used! This is usually due to differences in the operating system on which you run .NET Core. You will learn how to handle these exceptions in Chapter 2,Speaking C#.

The following diagram summarizes how the three variants of .NET (sometimes known as App Models) will share the common .NET Standard 2.0 and infrastructure:

The first edition of this book focused on .NET Core, but used .NET Framework when important or useful features had not yet been implemented in .NET Core. Visual Studio 2015 was used for most examples, with Visual Studio Code shown only briefly.

The second edition was almost completely purged of all .NET Framework code examples.

The third edition completes the job. It has been rewritten so that all of the code is pure .NET Core and can be written with Visual Studio 2017, Visual Studio for Mac, or Visual Studio Code on any supported operating system. The only exceptions are the last two chapters. In Chapter 17,Building Windows Apps Using XAML and Fluent Design, you will use .NET Core for UWP, which requires Visual Studio 2017 running on Windows 10, and in Chapter 18,Building Mobile Apps Using XAML and Xamarin.Forms, you will use Xamarin instead of .NET Core.

Understanding .NET Native

Another .NET initiative is .NET Native. This compiles C# code to native CPU instructions ahead-of-time (AoT), rather than using the CLR to compile intermediate language (IL) code just-in-time (JIT) to native code later.

.NET Native improves execution speed and reduces the memory footprint for applications. It supports the following:

  • UWP apps for Windows 10, Windows 10 Mobile, Xbox One, HoloLens, and Internet of Things (IoT) devices such as Raspberry Pi
  • Server-side web development with ASP.NET Core
  • Console applications for use on the command line

Comparing .NET technologies

The following table summarizes and compares .NET technologies:

Technology

Feature set

Compiles to

Host OSes

.NET Framework

Both legacy and modern

IL code

Windows only

Xamarin

Mobile only

IL code

iOS, Android, Windows Mobile

.NET Core

Modern only

IL code

Windows, macOS, Linux

.NET Native

Modern only

Native code

Windows, macOS, Linux

 

Writing and compiling code using the .NET Core CLI tool


When you install Visual Studio 2017, Visual Studio for Mac, or the .NET Core SDK, a Command-Line Interface (CLI) tool named dotnet is installed, as well as the .NET Core runtime.

Before we use CLI tools, such as dotnet, we need to write some code!

Writing code using a simple text editor

If you are using Windows, start Notepad.

If you are using macOS, launch TextEdit. Navigate to TextEdit | Preferences, clear the Smart quotes check box, and then close the dialog. Navigate to Format | Make Plain Text.

Alternatively, run your favorite plain text editor.

Enter the following code:

class MyApp { static void Main() {  
 System.Console.WriteLine("Hello, C#!"); } }

Note

C# is case sensitive, meaning that you must type uppercase and lowercase characters exactly as shown in the preceding code. C# is not whitespace sensitive, meaning that it does not care if you use tabs, spaces, or carriage-returns to layout your code however you like.

You can type the code all in one line, or spread it out over multiple lines and indent your lines. For example, the following code would also compile and have the same output:

class  
      MyApp      { 
 static                   void  
Main          (){System.       Console. 
    WriteLine(       "Hello, C#!");         }       } 

Of course, it's best to write your code in a way that other programmers, and yourself months or years later, can clearly read!

If you are using Windows Notepad

In Notepad, navigate to File | Save As....

In the Save As dialog, change to drive C: (or any drive which you want to use to save your projects), click on the New folder button, and name the folder Code. Open the Code folder, and click on the New folder button, and name the folder Chapter01. Open the Chapter01 folder, and click on the New folder button, and name the folder HelloCS. Open the HelloCS folder.

In the Save as type field, select All Files from the drop-down list to avoid appending the .txt file extension, and enter the filename as MyApp.cs, as shown in the following screenshot:

Your code in Notepad should look something like the following screenshot:

If you are using macOS TextEdit

In TextEdit, navigate to File | Save..., or press Cmd + S.

In the Save dialog, change to your user folder (mine is named markjprice) or any directory in which you want to use to save your projects, click on the New Folder button, and name the folder Code. Open the Code folder, and click on the New Folder button, and name the folder Chapter01. Open the Chapter01 folder, and click on the New Folder button, and name the folder HelloCS. Open the HelloCS folder.

In the Plain Text Encoding field, select Unicode (UTF-8) from the drop-down list, uncheck the box for If no extension is provided, use ".txt" to avoid appending the .txt file extension, enter the filename as MyApp.cs, and click on Save.

Creating and compiling apps using the .NET Core CLI tool

If you are using Windows, start Command Prompt.

If you are using macOS, launch Terminal.

At the prompt, enter the dotnet command and note the output, as shown in the following screenshot on macOS:

Note

The output from the dotnet command-line tool will be identical on Windows, macOS, and Linux.

Creating a console application at Command Prompt

Enter the following commands at the prompt to do the following:

  • Change to the folder for the project
  • Create a new console application in the directory
  • List the files that the dotnet command-line tool created

If you are using Windows, in Command Prompt, enter the following:

cd C:\Code\Chapter01\HelloCS
dotnet new console
dir

If you are using macOS, in Terminal, enter this:

cd Code/Chapter01/HelloCS
dotnet new console
ls

You should see that the dotnet tool has created two new files for you, as shown in the following screenshot on Windows:

  • Program.cs: Source code for a simple console application
  • HelloCS.csproj: A project file that lists dependencies and project-related configuration:

For this example, we must delete the file named Program.cs, since we have already created our own class in the file named MyApp.cs.

If you are using Windows, in Command Prompt, enter the following command:

del Program.cs

If you are using macOS, in Terminal, enter this:

rm Program.cs

Note

In all future examples, we will use the Program.cs file generated by the tool rather than manually create our own.

Restoring packages, compiling code, and running the application

At the prompt, enter the dotnet run command.

After a few seconds, all the packages needed by our code will be downloaded, the source code will be compiled, and your application will run, as shown in the following screenshot on macOS:

Your source code, the MyApp.cs file, has been compiled into an assembly named HelloCS.dll in the bin/Debug/netcoreapp2.0 subfolder. (Browse your filesystem for it if you like, I'll be waiting here for you to come back and continue.)

For now, this assembly can only be executed by the dotnet run command. In Chapter 7, Understanding and Packaging .NET Standard Types, you will learn how to package your compiled assemblies for use on any operating system that supports .NET Core.

Fixing compiler errors

If the compiler displays errors, read them carefully, and fix them in your text editor. Save your changes and try again.

Note

At the prompt, you can press the up and down arrows on your keyboard to cycle through previous commands you have entered.

A typical error might be using the wrong case, a missing semicolon at the end of a line, or a mismatched pair of curly braces. For example, if you mistyped a lowercase m for the Main method, you would see the following error message:

error CS5001: Program does not contain a static 'Main' method
suitable for an entry point

Understanding intermediate language

The C# compiler (named Roslyn) used by the dotnet CLI tool converts your C# source code into IL code, and stores the IL in an assembly (a DLL or EXE file).

IL code statements are like assembly language instructions, but they are executed by .NET Core's virtual machine, known as the CoreCLR.

At runtime, the CoreCLR loads the IL code from the assembly, JIT 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 process that generates code for the native operating system and CPU instruction set.

Regardless of which language the source is written in, for example, C# 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.

Note

Actually, not all .NET applications use IL code! Some use .NET Native's compiler to generate native code instead of IL code, improving performance and reducing memory footprint, but at the cost of portability.

 

Writing and compiling code using Visual Studio 2017


We will now create a similar application using Visual Studio 2017. If you have chosen to use Visual Studio for Mac or Visual Studio Code, I still recommend that you review these instructions and screenshots because Visual Studio for Mac and Visual Studio Code have similar, although not as extensive, features.

I have been training students to use Visual Studio for over a decade, and I am always surprised at how many programmers fail to use the tool to their advantage.

Over the next few pages, I will walk you through typing a line of code. It may seem redundant, but you will benefit from seeing what help and information Visual Studio provides as you enter your code. If you want to become a fast and accurate coder, letting Visual Studio write most of your code for you is a huge benefit!

Writing code using Microsoft Visual Studio 2017

Start Visual Studio 2017.

Navigate to File | New | Project... or press Ctrl + Shift + N.

From the Installed list on the left, expand Visual C#, and choose .NET Core. In the list at the center, choose Console App (.NET Core). Enter the name WelcomeDotNetCore, set the location to C:\Code, enter Chapter01 as the solution name, and click on OK or press Enter, as shown in the following screenshot:

Note

Ignore the target set to .NET Framework 4.7.1. That drop-down list box does not affect .NET Core projects!

In the code editor, delete the statement on line 9 that says the following:Console.WriteLine("Hello World!");

Inside the Main method, type the letters sy, as shown in the following screenshot, and note the IntelliSense menu that appears:

IntelliSense shows a filtered list of keywords, namespaces, and types that contain the letters sy and highlights the one that starts with sy, which happens to be the namespace that we want—System.

Type a dot (also known as decimal point or full stop).

IntelliSense automatically completes the word System for you, enters the dot, and displays a list of types, such as AggregateException and Action, in the System namespace, as shown in the following screenshot:

Type the letters con, IntelliSense shows a list of matching types and namespaces, as shown in the following screenshot:

We want Console. Press the down arrow on your keyboard to highlight it. When Console is selected, type a dot.

IntelliSense shows a list of the members of the Console class, as shown in the following screenshot:

Note

Members include properties (attributes of an object, such as BackgroundColor), methods (actions the object can perform, such as Beep), events, and other related things.

Type the letters wl. IntelliSense shows two matching members containing these letters in title case, WindowLeft and WriteLine, as shown in the following screenshot:

Use the down arrow to highlight WriteLine and then type an open parenthesis (.

IntelliSense autocompletes WriteLine and enters a pair of parentheses.

You will also see a tooltip telling you that the WriteLine method has 18 variations, as shown in the following screenshot:

Type a double quote ("). IntelliSense enters a pair of double quotes for you and leaves the keyboard cursor in between them.

Type the text Welcome, .NET Core!, as shown in the following screenshot:

The red squiggle at the end of the line indicates an error because every C# statement must end in a semicolon. Move the cursor to the end of the line and type a semicolon to fix the error.

Compiling code using Visual Studio 2017

Navigate to Debug | Start Without Debugging or press Ctrl + F5.

Visual Studio's status bar tells us that Build started..., then Build succeeded, and then your console application runs in a Command Prompt window, as shown in the following screenshot:

To save space in this book and to make the output clearer, I will usually not include screenshots of output from console applications as I did in the previous screenshot. Instead, I will show the output like this:

Welcome, .NET Core!

Fixing mistakes with the error list

Let's make two deliberate errors:

  • Change the M of the Main method to the lowercase letter m
  • Delete the e at the end of the method name, WriteLine

Navigate to Debug | Start Without Debugging or press Ctrl + F5.

After a few seconds, the status bar tells us that Build failed and an error message appears. Click on No.

Error List becomes active, as shown in the following screenshot:

The list can be filtered to show Errors, Warnings, and Messages by clicking on the toggle buttons in the toolbar at the top of the Error List window.

If an error shows a file and a line number, for example File: Program.cs and Line: 9, then you can double-click on the error to jump to that line causing the problem.

If it's a more general error, such as the missing Main method, the compiler can't tell you a useful line number. You might want a method named main as well as a method named Main (remember that C# is case sensitive, so you're allowed to do that).

However, Visual Studio can also analyze your code and highlight suggestions with three small grey dots under a potential problem. When you click on the dotted statement, a light bulb appears, and if you click on it, it provides suggestions for improvements, such as telling you that method names should begin with an uppercase character, as shown in the following screenshot:

As shown in the preceding screenshot, fix the two errors, and rerun the application to ensure that it works before you continue. Note that the Error List window updates to show no errors.

Adding existing projects to Visual Studio 2017

Earlier, you created a project using the dotnet CLI tool. Now that you have a solution in Visual Studio 2017, you might want to add the earlier project to the solution.

Navigate to File | Add | Existing Project..., browse to the C:\Code\Chapter01\HelloCS folder, and select the HelloCS.csproj file.

To be able to run this project, in Solution Explorer, right-click on Solution 'Chapter01' (2 projects), and choose Properties or press Alt + Enter.

For the Startup Project option, click on Current selection, and then click on OK.

In Solution Explorer, click on any file inside the HelloCS project, and then press Ctrl + F5, or navigate to Debug | Start Without Debugging.

Autoformatting code

Code is easier to read and understand if it is consistently indented and spaced out.

If your code can compile, then Visual Studio 2017 can automatically format it, nicely spaced and indented for you.

In Solution Explorer, double-click on the file named MyApp.cs, as shown in the following screenshot:

Navigate to Build | Build HelloCS or press Shift + F6, wait for your code to build, and then navigate to Edit | Advanced | Format Document, or press Ctrl + E, D. Your code will be autoformatted, as shown in the following screenshot:

Experimenting with C# Interactive

Although Visual Studio has always had an Immediate window with limited Read-eval-print loop (REPL) support, Visual Studio 2017 includes an enhanced window with full IntelliSense and color syntax code named C# Interactive.

In Visual Studio 2017, navigate to View | Other Windows | C# Interactive.

We will write some interactive code to download the About page from Microsoft's public website.

Note

This is just an example. You don't need to understand the code yet!

At the C# Interactive prompt, we will enter commands to do the following:

  • Reference the System.Net.Http assembly
  • Import the System.Net.Http namespace
  • Declare and instantiate an HTTP client variable
  • Set the client's base address to Microsoft's website
  • Asynchronously wait for a response to a GET request for the About page
  • Read the status code returned by the web server
  • Read the content type header
  • Read the contents of the HTML page as a string

Type each of the following commands after the > prompt, and then press Enter:

> #r "System.Net.Http"
> using System.Net.Http;
> var client = new HttpClient();
> client.BaseAddress = new Uri("http://www.microsoft.com/");
> var response = await client.GetAsync("about");
> response.StatusCode
OK
> response.Content.Headers.GetValues("Content-Type")
string[1] { "text/html" }
> await response.Content.ReadAsStringAsync()
"<!DOCTYPE html ><html 
xmlns:mscom="http://schemas.microsoft.com/CMSvNext" 
xmlns:md="http://schemas.microsoft.com/mscom-data" lang="en" 
xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="X-UA-
Compatible" content="IE=edge" /><meta charset="utf-8" /><meta 
name="viewport" content="width=device-width, initial-scale=1.0" 
/><link rel="shortcut icon" 
href="//www.microsoft.com/favicon.ico?v2" /><script 
type="text/javascript" 
src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-
1.7.2.min.js">rn // Third party scripts and code linked to 
or referenced from this website are licensed to you by the parties 
that own such code, not by Microsoft. See ASP.NET Ajax CDN Terms of 
Use - http://www.asp.net/ajaxlibrary/CDN.ashx.rn 
</script><script type="text/javascript" 
language="javascript">/*<![CDATA[*/if($(document).bind("mobileinit
",function(){$.mobile.autoInitializePage=!1}),navigator.userAgent.ma
tch(/IEMobile\/10\.0/)){var 
msViewportStyle=document.createElement("style ...

The following screenshot shows what Visual Studio 2017 should look like after you've entered the preceding commands into the C# Interactive window:

Note

Roslyn is the name of the C# compiler. Roslyn version 1.0 was for C# 6. Roslyn version 2.0 was for C# 7. Roslyn 2.3 and later is for C# 7.1.

Other useful windows

Visual Studio 2017 has lots of other useful windows, including the following:

  • Solution Explorer for managing projects and files
  • Team Explorer for source code management tools
  • Server Explorer for managing database connections and resources to manage in Microsoft Azure

If you can't see a window you need, go to the View menu to make it reappear or learn its keyboard shortcut, few of such shortcuts are shown in the following screenshot:

Note

If your keyboard shortcuts are different from the ones in the preceding screenshot, it is because you picked a different set when you installed Visual Studio. You can reset your keyboard shortcuts to match the ones used in this book by clicking on the Tools menu, then clicking on Import and Export Settings..., choosing Reset all settings, and then choosing to reset to the Visual C# settings collection.

 

Writing and compiling code using Visual Studio Code


The instructions and screenshots in this section are for macOS, but the same actions will work with Visual Studio Code on either Windows or Linux. The main differences will be native command-line actions such as deleting a file: both the command and the path are likely to be different. The dotnet CLI tool will be identical on all platforms.

Writing code using Visual Studio Code

Start Visual Studio Code.

Navigate to File | Open..., or press Cmd + O.

In the dialog, open the Code folder, select the Chapter01 folder, click on the New Folder button, enter the name WelcomeDotNetCore, and click on Create. Select the WelcomeDotNetCore folder, and click on Open or press Enter.

In Visual Studio Code, navigate to View | Integrated Terminal, or press Ctrl + `.

At the TERMINAL prompt, enter the following command:

dotnet new console

You will see that the dotnet command-line tool creates a new console application project for you in the current folder, and the Explorer window shows the two files created, as shown in the following screenshot:

In the EXPLORER window, click on the file named Program.cs to open it in the editor window.

If you see the warnings mentioning that the required assets are missing, click on Yes, as shown in the following screenshot:

Modify the text that is being written to the console to say, Welcome, .NET Core!

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

Compiling code using Visual Studio Code

Navigate to View | Integrated Terminal or press Ctrl + `, and enter the following command:

dotnet run

The output in the TERMINAL window will show the result of running your application.

Autoformatting code

In Visual Studio Code, navigate to File | Open, and open the Chapter01 folder.

In Explorer, expand HelloCS, and select MyApp.cs.

Click on Yes, when prompted to add required assets.

In Visual Studio Code, either right-click and choose Format Document, or press Alt + Shift + F, as shown in the following screenshot:

Visual Studio Code is rapidly approaching feature parity with Visual Studio 2017 on Windows.

 

Writing and compiling code using Visual Studio for Mac


Start Visual Studio for Mac, and navigate to File | New Solution.

In the list on the left, in the .NET Core section, select App.

In the project template list in the middle, select Console Application, and then click on Next, as shown in the following screenshot:

In the Configure your new Console Application step, select a Target Framework of .NET Core 2.0, and click on Next.

In the Configure your new Console Application step, enter Project Name as WelcomeDotNetCoreMac, enter Solution Name as Chapter01, set the Location to your Code folder, and click on Create, as shown in the following screenshot:

Modify the text that is being written to the console to say, Welcome, .NET Core on the Mac!

In Visual Studio for Mac, navigate to Run | Start Without Debugging, or press Cmd + Option + Enter.

The output in Terminal will show the result of running your application.

In the Solution pad, right-click on Chapter01, and go to Add | Add Existing Project....

In the HelloCS folder, select HelloCS.cs.proj.

In the Solution pad, right-click on HelloCS, and select Run Item, as shown in the following screenshot:

Next steps

You now know how to create and build simple .NET Core applications for Windows and macOS (and Linux is just as easy).

You will be able to complete almost all of the chapters in this book using Visual Studio 2017 on Windows, Visual Studio for Mac, or Visual Studio Code on Windows, macOS, or Linux.

 

Managing source code with GitHub


Gitis a commonly used source code management system. GitHub is a company, website, and desktop application that makes it easier to manage Git.

I used GitHub to store solutions to all the practical exercises at the end of each chapter at the following URL:

https://github.com/markjprice/cs7dotnetcore2

Using Git with Visual Studio 2017

Visual Studio 2017 has built-in support for using Git with GitHub as well as Microsoft's own source code management system named Visual Studio Team Services (VSTS).

Using the Team Explorer window

In Visual Studio 2017, navigate to View | Team Explorer, as shown in the following screenshot:

Although it is a good idea to sign up with an online source code management system provider, you can clone a GitHub repository without signing up for an account.

Cloning a GitHub repository

In the Team Explorer window, expand Local Git Repositories, click on the Clone menu, and then enter the following URL of a Git repository to clone it:

https://github.com/markjprice/cs7dotnetcore2.git

Enter a path for the cloned Git repository:

C:\Code\Repos\cs7dotnetcore2

Click on the Clone button, as shown in the following screenshot:

Wait for the Git repository to clone locally.

You will now have a local copy of the complete solutions to all of the hands-on practice exercises for this book.

Managing a GitHub repository

Double-click on the cs7dotnetcore2 repo to open a detail view.

You can click on the options in the Project section to view Pull Requests and Issues, and other aspects of a repository.

You can double-click on an entry in the Solutions section to open it in Solution Explorer.

Using Git with Visual Studio Code

Visual Studio Code has support for Git, but it will use your OS's Git installation, so you must install Git 2.0 or later first before you get these features. You can install Git from the following link:

https://git-scm.com/download

Note

If you like to use a GUI, you can download GitHub Desktop from the following link:https://desktop.github.com

Configuring Git at the command line

Launch Terminal, and enter the following command to check your configuration:

git config --list

The output should include your username and email address, because these will be used with every commit that you make:

...other congfiguration...
user.name=Mark J. Price
[email protected]

If your username and email has not been set, to set your username and email, enter the following commands, using your own name and email, not mine:

git config --global user.name "Mark J. Price"
git config --global user.email [email protected]

You can check an individual configuration setting like this:

git config user.name

Managing Git with Visual Studio Code

Launch Visual Studio Code, and open the Code folder.

Navigate toView | Integrated Terminal or press Ctrl + `, and enter the following commands:

mkdir Repos
cd Repos
git clone https://github.com/markjprice/cs7dotnetcore2.git

Cloning all of the solutions for all of the chapters to your local drive will take a minute, as shown in the following screenshot:

Note

For more information about source code version control with Visual Studio Code, visit the following link:https://code.visualstudio.com/Docs/editor/versioncontrol

 

Practicing and exploring


Test your knowledge and understanding by answering some questions, get some hands-on practice, and explore with deeper research into the topics covered in this chapter.

Exercise 1.1 – Test your knowledge

Answer the following questions:

  1. Why can a programmer use different languages, for example C# and F#, to write applications that run on .NET Core?
  2. What do you type at the prompt to build and execute C# source code?
  3. What is the Visual C# developer settings keyboard shortcut to save, compile, and run an application without attaching the debugger?
  4. What is the Visual Studio Code keyboard shortcut to view Integrated Terminal?
  5. Is Visual Studio 2017 better than Visual Studio Code?
  6. Is .NET Core better than .NET Framework?
  7. How is .NET Native different from .NET Core?
  8. What is .NET Standard and why is it important?
  9. What is the difference between Git and GitHub?
  10. What is the name of the entry-point method of a .NET console application and how should it be declared?

Exercise 1.2 – Practice C# anywhere

You do not need Visual Studio 2017, Visual Studio for Mac, or Visual Studio Code to practice writing C#.

Go to one of the following websites and start coding:

Exercise 1.3 – Explore topics

Use the following links to read more details about the topics covered in this chapter:

 

Summary


In this chapter, we set up the development environment, used Windows' Command Prompt and macOS's Terminal to compile and run a console application, used Visual Studio 2017, Visual Studio for Mac, and Visual Studio Code to create a similar application, and discussed the differences between .NET Framework, .NET Core, .NET Standard, and .NET Native.

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

About the Author

  • Mark J. Price

    Mark J. Price is a Microsof Certifed Trainer (MCT) and Microsof Specialist:

    • Programming in C# and Architecting Microsof Azure Solutions, with more than 20 years of educational and programming experience.

    Since 1993, Mark has passed more than 80 Microsof 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 experiences in consulting and developing systems for enterprises worldwide. Between 2001 and 2003, Mark was employed full time to write ofcial courseware for Microsof in Redmond, USA. His team wrote the frst training courses for C# while it was still an early alpha version. While with Microsof, 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 Cloud, the best .NET CMS for Digital Marketing and E-commerce. In 2010, Mark studied for a Postgraduate Certifcate 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.

    Browse publications by this author

Latest Reviews

(30 reviews total)
A very valuable ebook presenting C # programming in an interesting way and using .NET Core 2.0 technology as a multiplatform framework for programming web applications. I highly recommend everyone to consolidate and expand their knowledge and programming skills.
Sehr gut geschrieben. Hat mir viel geholfen.
El proceso de compra ha salido bien. Sin ningún contratiempo

Recommended For You

C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development - Fourth Edition

Learn the fundamentals, practical applications, and latest features of C# 8.0 and .NET Core 3.0 from expert teacher Mark J. Price.

By Mark J. Price
Hands-On Network Programming with C# and .NET Core

A comprehensive guide to understanding network architecture, communication protocols, and network analysis to build secure applications compatible with the latest versions of C# 8 and .NET Core 3.0

By Sean Burns
Hands-On Design Patterns with C# and .NET Core

Apply design patterns to solve problems in software architecture and programming using C# 7.x and .NET Core 2

By Gaurav Aroraa and 1 more
TensorFlow 2.0 Quick Start Guide

Perform supervised and unsupervised machine learning and learn advanced techniques such as training neural networks.

By Tony Holdroyd