43,19 €
The book has now been updated
Are you struggling to get started with C#? Or maybe you're interested in the potential of the new cross-platform features that .NET Core can offer? If so, C# 6 and .NET Core 1.0 is the book for you. While you don't need to know any of the latest features of C# or .NET to get started, it would be beneficial if you have some programming experience.
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.
This book takes a step-by-step approach and is filled with exciting projects and fascinating theory. It uses three high-impact sections to equip you with all the tools you'll need to build modern, cross-platform applications using C# and .NET Core.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 503
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: March 2016
Production reference: 1180316
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78528-569-1
www.packtpub.com
Author
Mark J. Price
Reviewers
Dustin Heffron
Liviu Ignat
Efraim Kyriakidis
Commissioning Editor
Edward Gordon
Acquisition Editor
Kirk D'Costa
Content Development Editor
Pooja Mhapsekar
Technical Editor
Vivek Pala
Copy Editor
Pranjali Chury
Project Coordinator
Francina Pinto
Proofreader
Safis Editing
Indexer
Tejal Soni
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
Mark J. Price is a Microsoft Certified Trainer (MCT) and Microsoft Specialist, Programming in C# and Architecting Microsoft Azure Solutions, with more than 20 years of educational and programming experience.
Since 1993, Mark has passed more than 90 Microsoft programming exams and specializes in preparing others to pass them too. His students range from professionals with decades of experience to 16-year-old apprentices with no experience at all. He successfully guides all of them by combining educational skills with real-world experience, consulting on and developing systems for enterprises worldwide.
Between 2001 and 2003, Mark was employed full-time to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# and .NET while they were still an early alpha version. While with Microsoft, he delivered "train-the-trainer" classes to get other MCTs up to speed in C# and .NET.
In 2010, Mark took a postgraduate certificate in education (PGCE). He taught GCSE and A-level mathematics in two secondary schools in London. Mark holds a Computer Science BSc (Hons) degree from the University of Bristol, UK.
I'd like to thank my parents, Pamela and Ian, for raising me to be polite, hardworking, and curious about the world. I'm grateful to my sisters, Emily and Juliet, for loving me despite being their awkward older brother. I'd also like to express my gratitude to my friends and colleagues who inspire me technically and creatively. Lastly, thanks to all the students I have taught over the years for making me strive to be a better teacher, especially Jared.
Dustin Heffron is a software engineer by day and an independent game developer by night. He has over 10 years of experience programming in various languages and 7 years of experience working with C# and .NET.
Currently, Dustin works as a software engineer for Johnson Controls Inc. He is also the cofounder and CEO of SunFlake Studios, which was founded in late 2015. He released his first commercial game, Squash Master, in early 2016 and is planning to develop additional games in the coming months and years.
Dustin has a long history of reviewing for Packt Publishing, including the book XNA 4.0 Game Development by Example: Beginner's Guide and the video tutorial series XNA 3D Programming by Example. He also coauthored the video tutorial series XNA 3D Toolkit with Larry Louisiana.
Liviu Ignat is a full-stack developer and architect, technology geek, and entrepreneur, who has been writing commercial software since 2004. He started with VB6, soon moved to .NET Java, and then continued by moving to front-end web development. He has fun with everything that is a functional language, such as F#, Scala, Swift, JavaScript, and so on.
Currently, he is a senior software engineer at AppDirect (http://appdirect.com), Munich, and he is also the CTO of his own startup (http://giftdoodle.com). He has been involved in building distributed backend services, mostly with .NET and complex single-page web apps. He is a big fan of microservices with C#, NodeJS, Scala, and Docker, single-page apps, and native apps with Android and IOS.
When he is not coding, Liviu loves snowboarding during the winter, sailing to exotic places during the summer, or just traveling the world. You can find and contact him at http://ignat.email/.
Efraim Kyriakidis is a skilled software engineer with over 10 years of experience in developing and delivering software solutions for diverse customers and projects. He's well-versed in all stages of the software development lifecycle. His first acquaintance with computers and programming was a state of the art Commodore 64, back in the '80s as a kid. Since then, he has grown up and received his diploma as Electro technic engineer from Aristotle University Thessaloniki in Greece. Through out his career he has mainly worked with Microsoft technologies, using C# and .NET since .NET 1.0. He currently works for Siemens AG in Germany as a software developer.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
There are many C# books, some, more than a thousand pages long, that aim to be comprehensive references to the C# programming language and the .NET Framework.
This book is different—it is concise and aims to be a fast-paced read that is packed with hands-on walkthroughs. I wrote this book to be the best step-by-step guide to modern cross-platform C# and .NET proven practices.
I will point out the cool corners and gotchas of C# so you can impress colleagues and employers and quickly get productive. Rather than slowing down and boring some of you by explaining every little thing, I assume that if a term I use is new to you, then you know how to Google it with a search engine such as DuckDuckGo.
At the end of each chapter, there is a section entitled Practicing and Exploring, which contains questions to test your knowledge, and usually a hands-on practical exercise, and you will explore topics in depth on your own with a little nudge in the right direction from me.
You can download solutions for the exercises from the GitHub repository at https://github.com/markjprice/cs6dotnetcore. I will provide instructions on how to do this using Visual Studio 2015 at the end of Chapter 1, Hello C#!, Welcome .NET Core!.
Chapter 1, Hello C#!, Welcome .NET Core!, is about setting up your development environment and using various tools to create the simplest application possible with C#. You will learn how to compile C# code at the Command Prompt and how to write and compile code using Visual Studio. You will also learn about the different .NET platforms: .NET Framework, .NET Core, and .NET Native.
Chapter 2, Speaking C#, is about the C# language, the grammar and vocabulary that you will use every day to write the source code for your applications. In particular, you will learn how to declare and work with variables of different types.
Chapter 3, Controlling the Flow, Converting Types, and Handling Exceptions, is about writing code that makes decisions, repeats blocks of statements, converts between types, and handles errors. You will also learn the best places to look for help.
Chapter 4, Using Common .NET Types, is about how .NET types are related to C#. You will learn about .NET Framework, .NET Core, and their class library assemblies of types that allow your applications to connect together existing components to perform common practical tasks.
Chapter 5, Using Specialized .NET Types, is about .NET types used to diagnose problems, support multiple languages and cultures, and access features and applications outside of .NET.
Chapter 6, Building Your Own Types with Object-Oriented Programming, is about all the different categories of members that a type can have, including fields for storing data and methods for performing actions. You will use OOP concepts such as aggregation and encapsulation.
Chapter 7, Implementing Interfaces and Inheriting Classes, is about deriving new types from existing ones using OOP. You will learn how to implement interfaces, about base and derived classes, how to override a type member, how to use polymorphism, and how to cast between classes in an inheritance hierarchy.
Chapter 8, Working with Relational Data Using the Entity Framework, is about reading and writing to Microsoft SQL Server (and other databases) using classic ADO.NET and the object-relational mapping technology known as Entity Framework.
Chapter 9, Querying and Manipulating Data with LINQ, is about Language Integrated Queries (LINQ)—language extensions that add the ability to work with sequences of items, and filter, sort, and project them into different outputs.
Chapter 10, Working with Files, Streams, and Serialization, is about reading and writing to files and streams, text encoding, and serialization.
Chapter 11, Protecting Your Data and Applications, is about protecting your data using encryption and hashing, and checking who is running your application and what they are allowed to do.
Chapter 12, Improving Performance and Scalability with Multitasking, is about allowing multiple actions to be executed at the same time to improve performance, scalability, and user productivity.
Chapter 13, Building Universal Windows Platform Apps Using XAML, is about learning the basics of XAML, which can be used to define the user interface for a graphical app for the Universal Windows Platform (UWP). This app can then run on Windows 10, Windows 10 Mobile, Xbox One, and even HoloLens.
Chapter 14, Building Web Applications and Services Using ASP.NET Core, is about building web applications and services using a modern HTTP architecture on the server side using Microsoft ASP.NET Core 1.0. You will learn about the models, views, and controllers that make up MVC and the Web API.
Chapter 15, Taking C# Cross-Platform, is about introducing you to how you can take C# cross-platform using .NET Core, ASP.NET Core 1.0, Entity Framework Core 1.0, and Visual Studio Code.
Chapter 16, Building a Quiz, is about designing and building a quiz application that helps students learn C#, .NET Core, and related topics.
Appendix A, Answers to the Test Your Knowledge Questions, has the answers to the test questions at the end of each chapter.
Appendix B, Creating a Virtual Machine for Your Development Environment, shows how to set up a virtual machine in Microsoft Azure for use as a development environment.
Although you can develop and deploy C# on many platforms, including Mac OS X and Linux, for the best learning experience, you need two pieces of software:
The best version of Windows to use is Microsoft Windows 10 because you need this version to create Universal Windows Platform apps in Chapter 13, Building Universal Windows Platform Apps Using XAML. Earlier versions of Windows, such as 7 or 8.1, will work for all other chapters. If you don't have a Windows computer, then you can use a virtual machine running Windows in the cloud. Refer to Appendix B, Creating a Virtual Machine for Your Development Environment for instructions.
The best version of Visual Studio to use is Microsoft Visual Studio Community 2015 with Update 1 (or later), which is the version I used while writing this book. In Chapter 15, Taking C# Cross-Platform, I will introduce you to Visual Studio Code, which runs on Windows, Linux, and Mac OS X, and can create cross-platform applications for all these OSes.
If you have heard that C# is a popular general-purpose, cross-platform programming language used to create everything from business applications, websites, and services to games for mobile devices, Xbox One, and the Windows 10 desktop-to-tablet-to-phone platform, then this book is for you.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
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:
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.
There are alternative IDEs for C#, for example, MonoDevelop, JetBrainsProject 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:
https://c9.io/web/sign-up/free
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.
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.
Download and install Microsoft Visual Studio Community 2015 with Update 1 or higher.
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.
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:
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.
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.
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:
https://signup.live.com/
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:
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:
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:
Year
C#
Features
2005
2
Generics with <T>
2008
3
Lambda expressions with => and manipulating sequences with LINQ (from, in, where, orderby, ascending, descending, select, group, into)
2010
4
Dynamic typing with dynamic and multithreading with Task
2012
5
Simplifying multithreading with async and await
2015
6
string interpolation with $"", importing static types with using static, and other refinements.
.NET Framework, .NET Core, and .NET Native are related platforms for developers to build applications and services upon.
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.
The open source community developed a cross-platform .NET implementation named the Mono project (http://www.mono-project.com/).
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.
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.
.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 .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.
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:
The following table summarizes and compares Microsoft's three .NET technologies:
Platform
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
When you install Visual Studio, other tools are installed too. One of those tools is the Developer Command Prompt for VS2015that has its path set to find developer tools such as the C# compiler.
Start Notepad (or your favorite text editor) and enter the following code:
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:
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:
Here are the commands:
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.
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:
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 theCommon 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 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:
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 (4.0.0.0) 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!
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.
To ensure