Search icon
Cart icon
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Learning Hub
Free Learning
Arrow right icon
Over 7,000 tech titles at $9.99 each with AI-powered learning assistants on new releases
C# 6 and .NET Core 1.0
C# 6 and .NET Core 1.0

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

$43.99 $9.99
Book Mar 2016 550 pages 1st Edition
$43.99 $9.99
$15.99 Monthly
$43.99 $9.99
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details

Publication date : Mar 29, 2016
Length 550 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781785285691
Vendor :
Category :
Table of content icon View table of contents Preview book icon Preview Book

C# 6 and .NET Core 1.0

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, and .NET Native, and using various tools to create the simplest application possible with C#.

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 of 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 1.0 during its rocky birth in the early months of 2016.

This chapter covers the following topics:

  • Setting up your development environment

  • Understanding the .NET Framework, .NET Core, and .NET Native

  • Writing and compiling code by using the Developer Command Prompt

  • Writing and compiling code by using Microsoft Visual Studio 2015

  • Targeting the .NET Core

  • Managing source code with GitHub

Setting up your development environment

Before you start programming, you will need to set up your Interactive Development Environment (IDE) that includes a code editor for C#. The best IDE to choose is Microsoft Visual Studio 2015, but it only runs on the Windows operating system.

Using alternative C# IDEs

There are alternative IDEs for C#, for example, MonoDevelop, JetBrains Project Rider, and Microsoft Visual Studio Code. They each have versions available for Windows, Linux, and Mac OS X, allowing you to write code on one operating system and deploy to the same, or a different, one:

Cloud9 is a web browser-based IDE, so it's even more cross-platform than the others. here is the link:

In Chapter 15, Taking C# Cross-Platform, I will show you how to use Visual Studio Code running on Mac OS X to create an ASP.NET Core 1.0 web application that can be deployed to Windows, Mac OS X, or Linux operating systems, or to Docker containers.


Linux and Docker are popular server host platforms because they are relatively lightweight and more cost-effectively scalable when compared to operating system platforms that are designed for end users, such as Windows and Mac OS X.

Using Visual Studio 2015 on Windows 10

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


If you don't have Windows, I recommend that you create a virtual machine (VM) to use for development. You can choose any cloud provider, but Microsoft Azure has preconfigured VMs that include properly licensed Windows and Visual Studio 2015. You only pay for the minutes your VM is running, so it is a way for users of Linux, Mac OS X, and older Windows versions to have all the benefits of using Visual Studio 2015. Refer to Appendix B, Creating a Virtual Machine for Your Development Environment for more information.

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


Microsoft has combined all its free developer offerings in a program called Visual Studio Dev Essentials. This includes the Community Edition, the free level of Visual Studio Team Services, Azure credits for test and development, and free training from Pluralsight, Wintellect, and Xamarin.

Installing Microsoft Visual Studio 2015

Download and install Microsoft Visual Studio Community 2015 with Update 1 or higher.

Choosing the default installation

If you prefer a smaller, faster installation then choose Default because it only requires 8 GB and should complete the installation in about an hour. With this choice, as shown in the following screenshot, you will be able to complete the first two-thirds of this book. To complete the rest of the book, you can later add additional features, such as support for building Universal Windows Platform (UWP) apps, via Programs and Features in the Control Panel:

If you chose Default, then skip to the Completing the Installation section.

Choosing the custom installation

If you have 34 GB of free disk space and can wait for several hours, then in the installation dialog, choose Custom, and then click on Next. Select the following features:

  • Under Windows and Web Development, tick the following checkboxes:

    • Microsoft SQL Server Data Tools

    • Microsoft Web Developer Tools

    • Universal Windows App Development Tools

  • Under Cross Platform Mobile Development, tick the following checkbox:

    • C#/.NET (Xamarin)

  • Under Common Tools, tick the following checkboxes:

    • Git for Windows

    • GitHub Extension for Visual Studio

Click on Next:


If you have the Home edition of Windows 10, then you will not be able to install emulators for Windows Phone because they require Hyper-V support.


You can choose to install everything if you want support for languages such as C++, Python, and F#, but these will not be covered in this book.

Completing the installation

On the license terms dialog, click on Install. Wait for the files to download and install.


While you wait for Visual Studio to install, you can jump to the Understanding .NET Framework, .NET Core, and .NET Native section in this chapter.

Signing in to Visual Studio

The first time that you run Visual Studio, you will be prompted to sign in:

If you have a Microsoft account, for example, a Hotmail, MSN, Live, or Outlook e-mail address, you can use that account. If you don't, then register for a new one at the following link:

Choosing development settings

After signing in, you will be prompted to choose Development Settings. Choose Visual C# to configure keyboard shortcuts and a default window layout that works best for C# programmers, as shown in the following screenshot:

After you click on Start Visual Studio, you will see the 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 window that will list all of your open projects, as shown in the following screenshot:

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:

Updating extensions and products

In the top-right corner of Visual Studio, you will see a flag that has a number next to it. These are notifications of extensions and product updates.

Click on the flag to display the Notifications window, as shown in the following screenshot:

In the Notifications window, click on each entry to install the update. You can install these updates at a later time if you prefer, but it is best to keep your software up-to-date to avoid bugs and security holes. The following screenshot shows an extension downloading and installing:

Using older versions of Visual Studio

If you want to use a free version of Visual Studio older than 2015, then you can use one of the more limited Express editions. A lot of the code in this book will work with older versions if you bear in mind when the following features were introduced:






Generics with <T>



Lambda expressions with => and manipulating sequences with LINQ (from, in, where, orderby, ascending, descending, select, group, into)



Dynamic typing with dynamic and multithreading with Task



Simplifying multithreading with async and await



string interpolation with $"", importing static types with using static, and other refinements.

Understanding .NET Framework, .NET Core, and .NET Native

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

Understanding .NET Framework platform

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

Microsoft designed the .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, the .NET Framework is Windows-only.

Understanding the Mono project

The open source community developed a cross-platform .NET implementation named the Mono project (

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

Understanding the .NET Core platform

Today, we live in a truly cross-platform world. Modern mobile and cloud development have made Windows a much less important operating system. So, Microsoft has been working on an effort to decouple the .NET Framework 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 the .NET Core 1.0, which includes a cross-platform implementation of the CLR, known as CoreCLR , and a streamlined library of classes known as CoreFX.

Streamlining .NET

.NET Core 1.0 is much smaller than the current version of the .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 the .NET Core. The latest technology for building Windows apps is the Universal Windows Platform (UWP). You will learn about it in Chapter 13, Building Universal Windows Platform Apps Using XAML.

ASP.NET Web Forms and Windows Communication Foundation (WCF) are old web applications and service technologies that fewer developers choose to use today, so they have also been removed from the .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 the .NET Core, named ASP.NET Core 1.0. You will learn about it in Chapter 14, Building Web Applications and Services Using ASP.NET Core.

The Entity Framework (EF) 6.x is an object-relational mapping technology for working 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 1.0. You will learn about it in Chapter 8, Working with Relational Data Using the Entity Framework.

Some data types in .NET that are included with both the .NET Framework and the .NET Core have been simplified by removing some members. For example, in the .NET Framework, the File class has both a Close and Dispose method, and either can be used to release the file resources. In .NET Core, there is only the Dispose method. This reduces the memory footprint of the assembly and simplifies the API.


The .NET Framework 4.6 is about 200 MB. The .NET Core 1.0 is about 11 MB. Eventually, the .NET Core may grow to a similar larger size. Microsoft's goal is not to make the .NET Core smaller than the .NET Framework. The goal is to componentize .NET Core to support modern technologies and to have fewer dependencies so that deployment requires only those components that your application really needs.

The future of .NET

The .NET Core is the future of .NET, but in my opinion, we are not there yet. .NET Core 1.0 is a great start, but it will take another version or two to become as mature as the current version of the .NET Framework.

This book will focus features available in .NET Core, but will use the .NET Framework when features have not (yet) been implemented in the .NET Core.


One of the reasons we picked this cover image for this book is that you can think of .NET Core as a new dawn for .NET. The .NET Framework has become overgrown, like a dense forest, and the .NET Core is like finding a clearing or glade within it. It's a fresh start.

Understanding the .NET Native platform

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

The .NET Native compiler 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 1.0

  • Console applications for use on the command line

Comparing .NET technologies

The following table summarizes and compares Microsoft's three .NET technologies:


Feature set

C# compiles to

Host OSes

.NET Framework

Mature and extensive

Intermediate Language (IL) code

Windows only

.NET Core

Brand-new and somewhat limited

Windows, Linux, Mac OS X, Docker

.NET Native

Brand-new and very limited

Native code

Writing and compiling code using the Developer Command Prompt

When you install Visual Studio, other tools are installed too. One of those tools is the Developer Command Prompt for VS2015 that has its path set to find developer tools such as the C# compiler.

Writing code using Notepad

Start Notepad (or your favorite text editor) and enter the following code:

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

You can type the code all on one line or spread it out over multiple lines and indent your lines to make it easier to read.


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 and spaces and carriage-returns to lay out your code however you like.

From the File menu, choose Save As.

In the dialog box, change to drive C: (or any drive that you want to use to save your projects), click on the New Folder button, and name the folder Code.

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

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

Compiling code using the Developer Command Prompt

Start the Developer Command Prompt for VS2015 by typing the letters deve in the Windows 10 Search box, as you can see in the following screenshot. You will also find it on the Start Menu or Start Screen listed in All apps in the Visual Studio 2015 folder:

At the Command Prompt, enter the commands to do the following:

  • Change to the C:\Code folder

  • Compile the source code using the C# compiler

  • Request a directory listing

  • Run the application by entering the name of the EXE

Here are the commands:

cd C:\Code
csc myfirstapp.cs

The output in the Command Prompt window should look like this:

Note that your source code, the file named myfirstapp.cs, has been compiled into an assembly named myfirstapp.exe. When you enter the name of the assembly, it is loaded and executed by .NET Framework 4.6 and its CLR.

You can copy the myfirstapp.exe file onto any computer with Windows 10 and it will run correctly because all copies of Windows 10 have .NET Framework 4.6 installed. Actually, you can copy the file onto a computer with an older version of Windows as long as it has .NET Framework 4.0 or later installed.

Fixing compiler errors

If the compiler displays errors, read them carefully, and fix them in Notepad. Save your changes and recompile.


At the Command 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 semi-colon at the end of a line, or a mismatched pair of curly braces. For example, if you had mistyped a lowercase m for the Main method you would see this error message:

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

Decompiling code using ILDASM

The C# compiler converts your 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, but they are executed by the .NET virtual machine known as the Common Language Runtime (CLR).

At runtime, the CLR 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 Mac OS X 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, all .NET applications use IL code for their instructions, stored in an assembly. Microsoft provides a tool that can open an assembly and reveal this IL code.


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

Disassembling compiled assemblies

Disassembling a compiled assembly is an advanced technique. I will walk you through the process, but do not worry about fully understanding what you are seeing yet!

Start the IL Disassembler by entering the following at the Developer Command Prompt:

ildasm myfirstapp.exe

You will see the IL DASM tool with the compiled EXE assembly loaded:

Double-click on MANIFEST in the tree view to show the metadata version (4.0.30319) of .NET and the Microsoft Core Library (mscorlib) assembly version ( that this assembly needs to run. The following screenshot tells us that to run this assembly, we would need .NET Framework 4.0 or later installed:

Close the MANIFEST window, expand Program, and then double-click on the Main method. Note the IL instructions: ldstr (load string), nop (no operation), and ret (return). Remember that IL is an assembly language that is executed by the .NET CLR:

Anyone can use this tool to see any .NET assembly's IL code. Don't panic! This is not a reason to avoid C#.

All applications are lists of instructions that must be visible to the machine that runs it. If the machine can read these instructions, so can anything else. Therefore, all software can be reverse-engineered. It's just a matter of the effort required. .NET just happens to make it very easy!


ILSpy is a popular open source tool that does everything IL DASM does and can also reverse-engineer the IL code into C# or Visual Basic .NET source code. I used this tool for a client who had lost the source code for an assembly and needed to recover it!

Writing and compiling code using Microsoft Visual Studio 2015

We will now recreate the same application using Microsoft Visual Studio 2015.

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 slowly 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, accurate coder, letting Visual Studio write most of your code for you is a huge benefit!

Writing code using Visual Studio 2015

Start Microsoft Visual Studio 2015.

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

At the top of the New Project dialog box, choose .NET Framework 4.6.1 (or later). From the Installed Templates list on the left, choose Visual C#. In the list at the center, choose Console Application. Enter the name Ch01_MyFirstApp, set the location to C:\Code, enter Chapter01 as the solution name, and click on OK or press Enter:

In the code editor, inside the Main method, press Enter to insert a new line between the innermost braces { }, and then type the letters sy, as you can see in the following screenshot:

Note that IntelliSense shows a list of keywords, namespaces, and types that contain the letters sy, and highlights the first 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 and namespaces, such as AccessViolationException and Action, in the System namespace, as shown in the following screenshot:

Type the letters con and IntelliSense shows a list of matching types and namespaces:

Press the down arrow on your keyboard to highlight Console, and then type a dot.

IntelliSense shows a list of the members of the Console class:


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

Type the letters wr. IntelliSense shows two matching members containing these letters:

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 19 variations:

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

Type the text Hello C#!, 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 by pressing End, and type a semicolon to fix the error.

Compiling code using Visual Studio

From the Debug menu, choose Start Without Debugging or press Ctrl + F5. Your completed application runs in a console window and closes when you press any key:

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

Hello C#!

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.

On the Build menu, choose Build Ch01_MyFirstApp or press Shift + F6.

After a few seconds, the status bar tells us that the build failed and the error list is activated. You can also view the error list by pressing Ctrl + W, E:

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

If an error shows the line number, for example Line 13 in the preceding screenshot, then you can double-click on the error to jump to the line causing the problem.

If it's a more general error, such as the missing Main method, the compiler can't tell you the 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).

Fix the two (as shown in the preceding screenshot) errors before you continue. Note that the error list updates to show no errors.

Experimenting with C# Interactive

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

On 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:

  • 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

  • Wait asynchronously 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("");
> var response = await client.GetAsync("about");
> response.StatusCode
> response.Content.Headers.GetValues("Content-Type")
string[1] { "text/html" }
> await response.Content.ReadAsStringAsync()
"<!DOCTYPE html ><html xmlns:mscom=\"\" xmlns:md=\"\" lang=\"en\" xmlns=\"\"><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=\"//\" /><script type=\"text/javascript\" src=\"\">\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 -\r\n    </script><script type=\"text/javascript\" language=\"javascript\">/*<![CDATA[*/if($(document).bind(\"mobileinit\",function(){$.mobile.autoInitializePage=!1}),navigator.userAgent.match(/IEMobile\\/10\\.0/)){var msViewportStyle=document.createElement(\"style ...

Other useful windows

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

  • The Solution Explorer window for managing all the projects and files you work on

  • The Team Explorer window for source code management tools, such as GitHub

  • The Server Explorer window for managing database connections

If you ever can't see a window you need, go to the View menu to make it reappear or learn its keyboard shortcut, as shown here:


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.

Targeting the .NET Core

For 15 years, .NET programmers have been targeting the .NET Framework, so there are many projects that may need to move from Windows-only to cross-platform by retargeting to the .NET Core.

Understanding the .NET Portability Analyzer

To ensure that a project will work cross-platform, we can install and run the Visual Studio 2015 extension named .NET Portability Analyzer.

It allows you to choose multiple platforms that you would like to target and then scans your compiled assemblies, passes a list of the types and methods that you use to a web service, and produces a report that lists which ones are not supported on each platform along with recommendations for fixes.

Installing the .NET Portability Analyzer

In Visual Studio, go to the Tools menu and choose Extensions and Updates….

On the left-hand side of the dialog, click on Online. In the Search Visual Studio Gallery box, type portability and press Enter.

Click on the .NET Portability Analyzer entry and then click on the Download button. Once the extension is installed, restart Visual Studio:

Configuring the .NET Portability Analyzer

In Visual Studio, go to the Tools menu and choose Options.

In the Options dialog box, scroll down through the left-hand side list and choose .NET Portability Analyzer. In the Target Platforms section, deselect everything except for the following:

  • .NET Core (Cross-platform) 1.0 (shown as 5.0 in the following screenshot)

  • .NET Framework 4.5

  • .NET Native 1.0

  • ASP.NET Core 1.0 (shown as ASP.NET 5 in the screenshot below):


Microsoft Azure has a Platform-as-a-Service (PaaS) feature named Cloud Services, which is limited to the .NET Framework 4.5; this is why it is a common target platform to check with the analyzer.

Analyzing a solution

In Visual Studio, open the previous solution, named Chapter01. In the Solution Explorer window, right-click on the project named Ch01_MyFirstApp (not the solution), choose Analyze, and then choose Analyze Assembly Portability.

After a few seconds, a report will display in the main area.


Be patient with the .NET Portability Analyzer because it has to send data to a web service and wait for a response.

Note that the Console class in the System namespace and its WriteLine method are supported by the following:

  • .NET Core (Cross-Platform) 1.0 (shown as 5.0 in the following screenshot)

  • .NET Framework 4.5

  • ASP.NET Core 1.0 (shown as ASP.NET 5 in the following screenshot)

However, it is not supported by .NET Native 1.0:


At the time of writing this, the .NET Portability Analyzer has not been updated to show the new version branding for .NET Core and related products, which can be found at

Press Ctrl + W, E to view the error list, which has also been populated. As we saw earlier, double-clicking on an error will jump the code editor to the line that could cause an issue:

.NET Portability and this book

I used the .NET Portability Analyzer while writing all the code in this book to ensure that, whenever possible, I can show you code that will work cross-platform using the .NET Core 1.0. If there are useful features that aren't cross-platform yet, then I will point that out in the text. Hopefully, they will be implemented in .NET Core in future versions.

Creating new projects for the .NET Core

Let's recreate the console application, but this time, target the .NET Core from the start.

Managing .NET Core development with Command Line Tools

There are two sets of command-line tools that you can use to manage the .NET Core:

  • .NET Version Manager, .NET Execution Environment, .NET Development Utilities (dnvm, dnx, dnu): These were used by Microsoft during the initial development of the .NET Core between 2013 and 2015. They are installed as part of Visual Studio 2015. These tools will be deprecated with the final release of the .NET Core.

  • .NET CLI (dotnet): This is a driver, which will be used by the final release of the .NET Core. It provides a simplified layer on top of other underlying tools. The .NET CLI must be installed separately.


At the time of writing, the DNX tools are more advanced than the .NET CLI, so in Chapter 15, Taking C# Cross-Platform, I will need to show you how to use both sets of tools. For this chapter, we can use the newer CLI tool because we are only using basic features. I recommend that you browse for information about changes between the time of writing this book and the release of the final versions of .NET Core 1.0 and its related technologies and tools.

Installing the .NET Command Line Tools

First, we must install the .NET Command Line Tools (CLI).

Start Microsoft Edge and go to the

Scroll down the page to find the Installers section and click on the link to download the MSI file for Windows. Open the file and install.

Creating a .NET Core application using Command Line Tools

Start the Developer Command Prompt for VS2015. At the prompt, enter the following command:


You should see the following output:

Enter the following at the prompt to create a new directory, change to it, create a new console application in the directory, and then list the files it created:

cd C:\Code\Chapter01
mkdir Ch01_MySecondApp
cd Ch01_MySecondApp
dotnet new

You should see that the dotnet tool has created three new files for you: NuGet.Config, Program.cs, and project.json.

At the prompt, enter the following to start Notepad for editing the Program class:

notepad Program.cs

In Notepad, modify the WriteLine statement as follows:

Console.WriteLine("Hello C#, Welcome .NET Core!");

Save changes and exit Notepad.

At the prompt, enter the following commands:

dotnet restore
dotnet run

After a few seconds, all the dependency packages will be downloaded and your application will run, showing the following output:

To compile the source code into an assembly containing IL code, enter the following command:

dotnet build

The output in the Command Prompt window should look like this:

Enter the following commands to change to a subdirectory, list the files in it, and execute the compiled console application:

cd bin\Debug\dnxcore50


The Debug is the name of the configuration and dnxcore50 is the name of the framework. This will change in the release version of the .NET Core.

Creating a .NET Core application using Visual Studio 2015

Start Visual Studio 2015 and open the Chapter01 solution.

In Visual Studio, navigate to File | Add | New Project.

In the Add New Project dialog box, in the Installed Templates list on the left-hand side, choose Visual C#. In the list at the center, choose Console Application (Package). Enter the name Ch01_DotNetCore, and click on OK or press Enter:

In the Solution Explorer window, right-click on the solution named Chapter01 and choose Properties.

Set the Startup Project to Current selection and click on OK.

Inside the Main method of the Program class, enter the following statements:

Console.WriteLine("Welcome, .NET Core!");

As you type code, you will notice that Visual Studio shows you which types and methods might not be available when targeting .NET Core. For example, the BufferHeight property is available when targeting the .NET Framework but not the .NET Core, as shown in the following screenshot as DNX 4.5.1 and DNX Core 5.0 respectively:

You can tell the compiler to include statements available only when .NET Framework is available by using conditional compilation symbols, as follows:

#if DNX451
    Console.BufferHeight = 300;
#elseif DNXCORE50
    // some alternative for .NET Core


In Chapter 5, Using Specialized .NET Types, you will learn more about conditional compilation symbols so that you can create projects that target both the .NET Framework and the .NET Core with a single code base.


The names of the conditional compilation symbols will change in the future. Visit for more information.

In the Solution Explorer window, double-click on Properties for the Ch01_DotNetCore project.

In the Properties window, click on the Debug tab, select the Use Specific Runtime checkbox, and select the latest version of the .NET Core platform for the x64 CPU architecture, as shown in the following screenshot:

In the Visual Studio Debug menu, choose Start or press F5.

Note that the Command Prompt window shows that the console application is running the dnx-coreclr-win-x64.1.0.0-rc1-update1 runtime:


Throughout the first half of this book, I will show example code by creating console applications, so you can decide if you want to target the .NET Framework by choosing Console Application, or target the .NET Core by choosing Console Application (Package).

Managing source code with GitHub

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

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

I used GitHub to store solutions to all the practical exercises at the end of each chapter.

Using the Team Explorer window

In Visual Studio, navigate to View | Team Explorer menu to see the Team Explorer window:

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:

Enter a path for the cloned Git repository:


Click on the Clone button:

Wait for the Git repository to clone locally:

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

Managing a GitHub repository

Double-click on the cs6dotnetcore 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 the Solution Explorer:

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 to write applications that run on .NET?

  2. What do you type at the Command Prompt to compile the C# source code?

  3. What is the Visual Studio 2015 keyboard shortcut to save, compile, and run an application, without attaching the debugger?

  4. What is the Visual Studio 2015 keyboard shortcut to view the error list?

  5. What does ildasm.exe do?

  6. Is the .NET Core better than the .NET Framework?

  7. How is .NET Native different from the .NET Core?

  8. What does the .NET Portability Analyzer do?

  9. What is the difference between Git and GitHub?

  10. What is the name of the entry-point method of a .NET application and how should it be declared?

Exercise 1.2 – practice managing Visual Studio Windows

Practice closing and viewing windows, such as Error List and Toolbox.

You can pin, unpin, float, and rearrange windows by dragging their title bars. As you do so, Visual Studio will show blue tinted boxes and overlays to help you to understand where the window will be moved when you release the mouse button.


You can always reset Visual Studio back to one of the default layouts by clicking on the Tools menu and Import and Export Settings….

Exercise 1.3 – practice coding anywhere

You do not need Visual Studio to practice writing C#. Simply go to the .NET Fiddle website ( and start coding. It's also a great way to share snippets of C# code with other developers:

Exercise 1.4 – explore topics

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


In this chapter, we set up the development environment, we used the Developer Command Prompt to compile and decompile an application, we used Visual Studio to create the same application and explore the features that make it so easy to use for development, and we discussed the differences between the .NET Framework, the .NET Core, and .NET Native.

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

Left arrow icon Right arrow icon

Key benefits

  • [•] Build modern, cross-platform applications with .NET Core 1.0
  • [•] Get up-to-speed with C#, and up-to-date with all the latest features of C# 6
  • [•] Start creating professional web applications with ASP.NET Core 1.0


With the release of .NET Core 1.0, you can now create applications for Mac OS X and Linux, as well as Windows, using the development tools you know and love. C# 6 and .NET Core 1.0 has been divided into three high-impact sections to help start putting these new features to work. First, we'll run you through the basics of C#, as well as object-orient programming, before taking a quick tour through the latest features of C# 6 such as string interpolation for easier variable value output, exception filtering, and how to perform static class imports. We'll also cover both the full-feature, mature .NET Framework and the new, cross-platform .NET Core. After quickly taking you through C# and how .NET works, we'll dive into the internals of the .NET class libraries, covering topics such as performance, monitoring, debugging, internationalization, serialization, and encryption. We'll look at Entity Framework Core 1.0 and how to develop Code-First entity data models, as well as how to use LINQ to query and manipulate that data. The final section will demonstrate the major types of applications that you can build and deploy cross-device and cross-platform. In this section, we'll cover Universal Windows Platform (UWP) apps, web applications, and web services. Lastly, we'll help you build a complete application that can be hosted on all of today's most popular platforms, including Linux and Docker. 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 Core.

What you will learn

[•] Build cross-platform applications using C# 6 and .NET Core 1.0 [•] Explore ASP.NET Core 1.0 and learn how to create professional web applications [•] Improve your application’s performance using multitasking [•] Use Entity Framework Core 1.0 and learn how to build Code-First databases [•] Master object-oriented programming with C# to increase code reuse and efficiency [•] Familiarize yourself with cross-device app development using the Universal Windows Platform and XAML [•] Query and manipulate data using LINQ [•] Protect your data by using encryption and hashing

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details

Publication date : Mar 29, 2016
Length 550 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781785285691
Vendor :
Category :

Table of Contents

25 Chapters
C# 6 and .NET Core 1.0 Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. Hello, C#! Welcome, .NET Core! Chevron down icon Chevron up icon
2. Speaking C# Chevron down icon Chevron up icon
3. Controlling the Flow, Converting Types, and Handling Exceptions Chevron down icon Chevron up icon
4. Using Common .NET Types Chevron down icon Chevron up icon
5. Using Specialized .NET Types Chevron down icon Chevron up icon
6. Building Your Own Types with Object-Oriented Programming Chevron down icon Chevron up icon
7. Implementing Interfaces and Inheriting Classes Chevron down icon Chevron up icon
8. Working with Relational Data Using the Entity Framework Chevron down icon Chevron up icon
9. Querying and Manipulating Data with LINQ Chevron down icon Chevron up icon
10. Working with Files, Streams, and Serialization Chevron down icon Chevron up icon
11. Protecting Your Data and Applications Chevron down icon Chevron up icon
12. Improving Performance and Scalability with Multitasking Chevron down icon Chevron up icon
13. Building Universal Windows Platform Apps Using XAML Chevron down icon Chevron up icon
14. Building Web Applications and Services Using ASP.NET Core Chevron down icon Chevron up icon
15. Taking C# Cross-Platform Chevron down icon Chevron up icon
16. Building a Quiz Chevron down icon Chevron up icon
Answers to the Test Your Knowledge Questions Chevron down icon Chevron up icon
Creating a Virtual Machine for Your Development Environment Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by

No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial


How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to
  • To contact us directly if a problem is not resolved, use
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.