
C# 7 and .NET Core: Modern Cross-Platform Development

We will now recreate a similar application using Visual Studio 2017. If you have chosen to use Visual Studio Code, I still recommend that you review these instructions and screenshots because Visual Studio Code has 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!
Start Visual Studio 2017.
Navigate to File | New | Project... or press Ctrl + Shift + N.
From the Installed | Templates 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 Ch01_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:
Ignore the target set to .NET Framework 4.6.2. That drop-down list box does not affect .NET Core projects!
In the code editor, delete the statement on line 9 that says, 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:
If the one you want is not selected, you can press the up and down arrows on your keyboard to highlight it. For now, Console is already selected, so just type a dot.
IntelliSense shows a list of the members of the Console
class, as shown in the following screenshot:
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 wr
. IntelliSense shows two matching members containing these letters, 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.
From the Debug menu, choose 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!
Let's make two deliberate errors:
M
of the Main
method to the lowercase letter m
.e
at the end of the method name, WriteLine
.From the Debug menu, choose Start Without Debugging or press Ctrl + F5.
After a few seconds, the status bar tells us that Build failed and an error message appears, as shown in the following screenshot:
Click No.
The Error List becomes active, as shown in the following screenshot. You can also view the Error List by pressing Ctrl + W, E:
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.
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 provide messages with suggestions for improvements, such as telling you that method names should begin with an uppercase character.
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 updates to show no errors.
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 folder C:\Code\Chapter01\Ch01_HelloCS
, and select the file Ch01_HelloCS.csproj
.
To be able to run this project, in the Solution Explorer, right-click Solution 'Chapter01' (2 projects), and choose Properties or press Alt + Enter.
For the Startup Project, click Current selection, and click OK.
In Solution Explorer, click on any file inside the Ch01_HelloCS
project, and then press Ctrl + F5, or navigate to Debug | Start Without Debugging.
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 the file named MyApp.cs
, as shown in the following screenshot:
Navigate to Build | Build Ch01_HelloCS, or press Shift + F6 and 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:
In Visual Studio Code, either right-click and choose Format Document, or press Alt + Shift + F.
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, from the View menu, choose Other Windows, and then C# Interactive.
We will write some interactive code to download the About page from Microsoft's public website.
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:
System.Net.Http
assemblySystem.Net.Http
namespaceType 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">\r\n // 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.\r\n
</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 above commands into the C# Interactive window:
Roslyn is the name of the C# compiler. Roslyn version 1.0 was for C# 6. Roslyn version 2.0 is for C# 7.
Visual Studio 2017 has lots of other useful windows, including the following:
If you can't see a window you need, go to the View menu to make it reappear or learn its keyboard shortcut, some of which are shown in the following screenshot:
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.
Change the font size
Change margin width
Change background colour