Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Beginning C# 7 Programming with Visual Studio 2017
Beginning C# 7 Programming with Visual Studio 2017
Beginning C# 7 Programming with Visual Studio 2017
Ebook1,604 pages9 hours

Beginning C# 7 Programming with Visual Studio 2017

Rating: 0 out of 5 stars

()

Read preview

About this ebook

 Easily get started programming using the ultra-versatile C# 7 and Visual Studio 2017

Beginning C# 7 Programming with Visual Studio 2017 is the beginner’s ultimate guide to the world’s most popular programming language. Whether you’re new to programming entirely, or just new to C#, there has never been a better time to get started. The new C# 7 and Visual Studio 2017 updates feature a number of new tools and features that streamline the workflow, simplify the code, and make it easier than ever to build high-quality apps. This book walks you through everything you need to know, starting from the very basics, to have you programming in no time. You’ll learn about variables, flow control, and object oriented programming, then move into Web and Windows programming as well as databases and XML. The companion website provides downloadable code examples, and practical Try It Out sections provide explicit, step-by-step instructions for writing your own useful, customizable code.

C# 7 can be used to build Windows applications, program Windows 10, and write Web apps when used alongside ASP.NET. With programming skills becoming de rigueur in fields far beyond the tech world, C# 7 is a great place to start building versatile, helpful skills. This book gets you started quickly and easily with instruction from a master-team of C# programmers.

  • Learn how to program using the world’s leading programming language
  • Build smarter, faster apps using the latest features in C# 7 and Visual Studio 2017
  • Find and fix bugs sooner, saving headaches down the line
  • Integrate with all .NET Core, Azure applications, cloud services, Docker containers, and more

The world of programming can seem intimidating to a beginner, and the prospect of learning a whole new “language” can seem daunting. Beginning C# 7 Programming with Visual Studio 2017 demystifies the process and shows you how to bring your ideas to life.

LanguageEnglish
PublisherWiley
Release dateMar 20, 2018
ISBN9781119458661
Beginning C# 7 Programming with Visual Studio 2017

Read more from Benjamin Perkins

Related to Beginning C# 7 Programming with Visual Studio 2017

Related ebooks

Programming For You

View More

Related articles

Reviews for Beginning C# 7 Programming with Visual Studio 2017

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Beginning C# 7 Programming with Visual Studio 2017 - Benjamin Perkins

    INTRODUCTION

    THE C# LANGUAGE WAS UNVEILED TO THE WORLD when Microsoft announced the first version of its .NET Framework in July 2000. Since then its popularity has rocketed, and it has arguably become the language of choice for desktop, web, cloud, and cross‐platform developers who use the .NET Framework. Part of the appeal of C# comes from its clear syntax, which derives from C/C++ but simplifies some things that have previously discouraged some programmers. Despite this simplification, C# has retained the power of C++, and there is now no reason not to move into C#. The language is not difficult and it's a great one to learn elementary programming techniques with. This ease of learning, combined with the capabilities of the .NET Framework, make C# an excellent way to start your programming career.

    The latest release of C# is C# 7 (included with version 4.7 of the .NET Framework), which builds on the existing successes and adds even more attractive features. The latest release of Visual Studio (Visual Studio 2017) and the Visual Studio Code 2017 line of development tools also bring many tweaks and improvements to make your life easier and to dramatically increase your productivity.

    This book is intended to teach you about all aspects of C# programming, including the language itself, desktop, cloud, and cross‐platform programming, making use of data sources, and some new and advanced techniques. You'll also learn about the capabilities of Visual Studio 2017 and all the ways that this product can aid your application development.

    The book is written in a friendly, mentor‐style fashion, with each chapter building on previous ones, and every effort is made to ease you into advanced techniques painlessly. At no point will technical terms appear from nowhere to discourage you from continuing; every concept is introduced and discussed as required. Technical jargon is kept to a minimum, but where it is necessary, it, too, is properly defined and laid out in context.

    The authors of this book are all experts in their field and are all enthusiastic in their passion for both the C# language and the .NET Framework. Nowhere will you find a group of people better qualified to take you under their collective wing and nurture your understanding of C# from first principles to advanced techniques. Along with the fundamental knowledge it provides, this book is packed full of helpful hints, tips, exercises, and full‐fledged example code (available for download on this book's web page at www.wrox.com and at https://github.com/benperk/BeginningCSharp7) that you will find yourself returning to repeatedly as your career progresses.

    We pass this knowledge on without begrudging it and hope that you will be able to use it to become the best programmer you can be. Good luck, and all the best!

    WHO THIS BOOK IS FOR

    This book is for everyone who wants to learn how to program in C# using the .NET Framework. It is for absolute beginners who want to give programming a try by learning a clean, modern, elegant programming language. But it is also for people familiar with other programming languages who want to explore the .NET platform, as well as for existing .NET developers who want to give Microsoft's .NET flagship language a try.

    WHAT THIS BOOK COVERS

    The early chapters cover the language itself, assuming no prior programming experience. If you have programmed in other languages before, much of the material in these chapters will be familiar. Many aspects of C# syntax are shared with other languages, and many structures are common to practically all programming languages (such as looping and branching structures). However, even if you are an experienced programmer, you will benefit from looking through these chapters to learn the specifics of how these techniques apply to C#.

    If you are new to programming, you should start from the beginning, where you will learn basic programming concepts and become acquainted with both C# and the .NET platform that underpins it. If you are new to the .NET Framework but know how to program, you should read Chapter 1 and then skim through the next few chapters before continuing with the application of the C# language. If you know how to program but haven't encountered an object‐oriented programming language before, you should read the chapters from Chapter 8 onward.

    Alternatively, if you already know the C# language, you might want to concentrate on the chapters dealing with the most recent .NET Framework and C# language developments, specifically the chapters on collections, generics, and C# language enhancements (Chapters 11 and 12).

    The chapters in this book have been written with a dual purpose in mind: They can be read sequentially to provide a complete tutorial in the C# language, and they can be dipped into as required reference material.

    In addition to the core material, starting with Chapter 3 most chapters also include a selection of exercises at the end, which you can work through to ensure that you have understood the material. The exercises range from simple multiple choice or true/false questions to more complex exercises that require you to modify or build applications. The answers to all the exercises are provided in the Appendix. You can also find these exercises as part of the wrox.com code downloads on this book's page at www.wrox.com.

    This book also gives plenty of love and attention to coincide with the release of C# 7 and .NET 4.7. Every chapter received an overhaul, with less relevant material removed, and new material added. All of the code has been tested against the latest version of the development tools used, and all of the screenshots have been retaken in Windows 10 to provide the most current windows and dialog boxes. New highlights of this edition include the following:

    Additional and improved code examples for you to try out

    Coverage of everything that's new in C# 7 and .NET 4.7

    Examples of programming .NET Core and ASP.NET Core for running cross‐platform

    Examples of programming cloud applications and using Azure SDK to create and access cloud resources

    HOW THIS BOOK IS STRUCTURED

    This book is divided into six sections:

    Introduction—Purpose and general outline of the book's contents

    The C# Language—Covers all aspects of the C# language, from the fundamentals to object‐oriented techniques

    Windows Programming—How to write and deploy desktop applications with the Windows Presentation Foundation library (WPF)

    Cloud and Cross‐Platform Programming—Cloud and cross‐platform application development and deployment, including the creation and consumption of a Web API

    Data Access—How to use data in your applications, including data stored in files on your hard disk, data stored in XML format, and data in databases

    Additional Techniques—An examination of some extra ways to use C# and the .NET Framework, including Windows Communication Foundation (WCF) and Universal Windows Applications

    The following sections describe the chapters in the five major parts of this book.

    The C# Language (Chapters 1– 13 )

    Chapter 1 introduces you to C# and how it fits into the .NET landscape. You'll learn the fundamentals of programming in this environment and how Visual Studio 2017 (VS) fits in.

    Chapter 2 starts you off with writing C# applications. You'll look at the syntax of C# and put the language to use with sample command‐line and Windows applications. These examples demonstrate just how quick and easy it can be to get up and running, and along the way you'll be introduced to the Visual Studio development environment and the basic windows and tools that you'll be using throughout the book.

    Next, you'll learn more about the basics of the C# language. You'll learn what variables are and how to manipulate them in Chapter 3. You'll enhance the structure of your applications with flow control (looping and branching) in Chapter 4, and you'll see some more advanced variable types such as arrays in Chapter 5. In Chapter 6 you'll start to encapsulate your code in the form of functions, which makes it much easier to perform repetitive operations and makes your code much more readable.

    By the beginning of Chapter 7 you'll have a handle on the fundamentals of the C# language, and you will focus on debugging your applications. This involves looking at outputting trace information as your applications are executed, and at how Visual Studio can be used to trap errors and lead you to solutions for them with its powerful debugging environment.

    From Chapter 8 onward you'll learn about object‐oriented programming (OOP), starting with a look at what this term means and an answer to the eternal question, What is an object? OOP can seem quite difficult at first. The whole of Chapter 8 is devoted to demystifying it and explaining what makes it so great, and you won't actually deal with much C# code until the very end of the chapter.

    Everything changes in Chapter 9, when you put theory into practice and start using OOP in your C# applications. This is where the true power of C# lies. You'll start by looking at how to define classes and interfaces, and then move on to class members (including fields, properties, and methods) in Chapter 10. At the end of that chapter you'll start to assemble a card game application, which is developed over several chapters and will help to illustrate OOP.

    Once you've learned how OOP works in C#, Chapter 11 moves on to look at common OOP scenarios, including dealing with collections of objects, and comparing and converting objects. Chapter 12 takes a look at a very useful feature of C# that was introduced in .NET 2.0: generics, which enable you to create very flexible classes. Next, Chapter 13 continues the discussion of the C# language and OOP with some additional techniques, notably events, which become very important in, for example, Windows programming. Chapter 13 wraps up the fundamentals by focusing on C# language features that were introduced with versions 3.0, 4, 5, and 6 of the language.

    Windows Programming (Chapters 14– 15 )

    Chapter 14 starts by introducing you to what is meant by Windows programming and looks at how this is achieved in Visual Studio. It focuses on WPF as a tool that enables you to build desktop applications in a graphical way and assemble advanced applications with the minimum of effort and time. You'll start with the basics of WPF programming and build up your knowledge in both this chapter and Chapter 15, which demonstrates how you can use the wealth of controls supplied by the .NET Framework in your applications.

    Cloud and Cross‐Platform Programming (Chapters 16– 19 )

    Chapter 16 starts by describing what cloud programming is and discusses the cloud‐optimized stack. The cloud environment is not identical to the way programs have been traditionally coded, so a few cloud programming patterns are discussed and defined. To complete this chapter, you require an Azure account, which is free, so that you can create an App Service Web App. Then, using the Azure SDK with C#, you create and access a storage account from an ASP.NET 4.7 web application.

    In Chapter 17, you learn how to create and deploy an ASP.NET Web API to the cloud and then consume the Web API from a similar ASP.NET 4.7 web application. The chapter ends discussing two of the most valuable features in the cloud, scaling and the optimal utilization of hardware resources.

    Chapter 18 introduces .NET Standard and .NET Core, which are tools used for targeting any application type—for example WPF, Windows, and ASP.NET. An emerging application is one that can run cross‐platform such as on Linux or MacOS. The chapter provides instructions for installing .NET Core 2.0 and creating and implementing a .NET Standard library.

    Chapter 19 describes ASP.NET and its many different types (e.g., ASP.NET Webforms, ASP.NET MVC, and ASP.NET Core). The exercises in this chapter utilize the .NET Standard library created in Chapter 18 from both an ASP.NET Webpage and an ASP.NET Core application.

    Data Access (Chapters 20– 23 )

    Chapter 20 looks at how your applications can save and retrieve data to disk, both as simple text files and as more complex representations of data. You'll also learn how to compress data and how to monitor and act on file system changes.

    In Chapter 21 you'll learn about the de facto standard for data exchange—namely XML—and a rapidly emerging format called JSON. By this point in the book, you'll have touched on XML several times in preceding chapters, but this chapter lays out the ground rules and shows you what all the excitement is about.

    The remainder of this part looks at LINQ, which is a query language built in to the latest versions of the .NET Framework. You start in Chapter 22 with a general introduction to LINQ, and then you will use LINQ to access a database and other data in Chapter 23.

    Additional Techniques (Chapters 24– 25 )

    Chapter 24 is an introduction to Windows Communication Foundation (WCF), which provides you with the tools you need for enterprise‐level programmatic access to information and capabilities across local networks and the Internet. You will see how you can use WCF to expose complex data and functionality to web and desktop applications in a platform‐independent way.

    Chapter 25 shows you how you can create Universal Windows Apps, which are new to Windows. This chapter builds on the foundation of Chapters 14 and 15 to show you how to create Windows Apps that can run on all windows platforms.

    WHAT YOU NEED TO USE THIS BOOK

    The code and descriptions of C# and the .NET Framework in this book apply to C# 7 and .NET 4.7. You don't need anything other than the Framework to understand this aspect of the book, but many of the examples require a development tool. This book uses Visual Studio Community 2017 as its primary development tool. Use Visual Studio Community 2017 to create Windows, cloud, and cross‐platform applications as well as SQL Server Express for applications that access databases. Some functionality is available only in Visual Studio 2017, but this won't stop you from working through any of the examples in this book.

    The source code for the samples is available for download from this book's page on www.wrox.com and at https://github.com/benperk/BeginningCSharp7.

    CONVENTIONS

    To help you get the most from the text and keep track of what's happening, we've used a number of conventions throughout the book.

    TRY IT OUT

    The Try It Out is an exercise you should work through, following the text in the book.

    These exercises usually consist of a set of steps.

    Each step has a number.

    Follow the steps through with your copy of the database.

    How It Works

    After each Try It Out, the code you've typed will be explained in detail.

    WARNING

    Warnings hold important, not‐to‐be‐forgotten information that is directly relevant to the surrounding text.

    NOTE

    Shaded boxes like this hold notes, tips, hints, tricks, or asides to the current discussion.

    As for styles in the text:

    We italicize new terms and important words when we introduce them.

    We show keyboard strokes like this: Ctrl+A.

    We show file names, URLs, and code within the text like so: persistence.properties

    We present code in two different ways:

    We use a monofont type with no highlighting for most code examples. We use bold to emphasize code that is particularly important in the present context or to show changes from a previous code snippet.

    SOURCE CODE

    As you work through the examples in this book, you may choose either to type in all the code manually, or to use the source code files that accompany the book. All the source code used in this book is available for download on this book's page at www.wrox.com and at https://github.com/benperk/BeginningCSharp7.

    You can also search for the book at www.wrox.com by ISBN (the ISBN for this book is 978‐1‐119‐45868‐5) to find the code. A complete list of code downloads for all current Wrox books is available at www.wrox.com/dynamic/books/download.aspx.

    Most of the code on www.wrox.com is compressed in a .ZIP, .RAR archive, or similar archive format appropriate to the platform. Once you download the code, just decompress it with an appropriate compression tool.

    NOTE

    Because many books have similar titles, you may find it easiest to search by ISBN; this book's ISBN is 978‐1‐119‐45868‐5.

    Alternatively, as just mentioned, you can also go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

    ERRATA

    We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration, and at the same time, you will be helping us provide even higher quality information.

    To find the errata page for this book, go to this book's page at www.wrox.com and click the Errata link. On this page you can view all errata that has been submitted for this book and posted by Wrox editors.

    If you don't spot your error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We'll check the information and, if appropriate, post a message to the book's errata page and fix the problem in subsequent editions of the book.

    PART I

    The C# Language

    CHAPTER 1: Introducing C#

    CHAPTER 2: Writing a C# Program

    CHAPTER 3: Variables and Expressions

    CHAPTER 4: Flow Control

    CHAPTER 5: More about Variables

    CHAPTER 6: Functions

    CHAPTER 7: Debugging and Error Handling

    CHAPTER 8: Introduction to Object-Oriented Programming

    CHAPTER 9: Defining Classes

    CHAPTER 10: Defining Class Members

    CHAPTER 11: Collections, Comparisons, and Conversions

    CHAPTER 12: Generics

    CHAPTER 13: Additional C# Techniques

    1

    Introducing C#

    WHAT YOU WILL LEARN IN THIS CHAPTER

    What the .NET Framework is

    What C# is

    Explore Visual Studio 2017

    Welcome to the first chapter of the first section of this book. This section provides you with the basic knowledge you need to get up and running with the most recent version of C#. Specifically, this chapter provides an overview of the .NET Framework and C#, including what these technologies are, the motivation for using them, and how they relate to each other.

    It begins with a general discussion of the .NET Framework. This technology contains many concepts that are tricky to come to grips with initially. This means that the discussion, by necessity, covers many concepts in a short amount of space. However, a quick look at the basics is essential to understanding how to program in C#. Later in the book, you revisit many of the topics covered here, exploring them in more detail.

    After that general introduction, the chapter provides a basic description of C# itself, including its origins and similarities to C++. Finally, you look at the primary tool used throughout this book: Visual Studio (VS). Visual Studio 2017 is the latest in a long line of development environments that Microsoft has produced, and it includes all sorts of features (including full support for Windows Store, Azure, and cross‐platform applications) that you will learn about throughout this book.

    WHAT IS THE .NET FRAMEWORK?

    The .NET Framework (now at version 4.7) is a revolutionary platform created by Microsoft for developing applications. The most interesting thing about this statement is how vague and limited it is—but there are good reasons for this. To begin with, note that it doesn't actually develop applications only on the Windows operating system. Although the Microsoft release of the .NET Framework runs on the Windows and Windows Mobile operating systems, it is possible to find alternative versions that will work on other systems. One example of this is Mono, an open source version of the .NET Framework (including a C# compiler) that runs on several operating systems, including various ‐flavors of Linux and Mac OS; you can read more about it at http://www.mono‐project.com.

    Mono is a very important part of the .NET ecosystem, especially for creating client‐side applications with Xamarin. Microsoft has also created a cross platform open source library called .NET Core (https://github.com/dotnet/core) which they hope will have a positive impact on both the Mono and .NET Core frameworks. Programmers in both ecosystems can use examples from each other's libraries to improve performance, security, and the breadth of language feature offerings—collaboration is a key characteristic in the open source community.

    In addition, the definition of the .NET Framework includes no restriction on the type of applications that are possible. The .NET Framework enables the creation of desktop applications, Windows Store (UWP) applications, cloud/web applications, Web APIs, and pretty much anything else you can think of. Also, it's worth noting that web, cloud, and Web API applications are, by definition, multi‐platform applications, since any system with a web browser can access them.

    The .NET Framework has been designed so that it can be used from any language, including C# (the subject of this book) as well as C++, F#, JScript, Visual Basic, and even older languages such as COBOL. For this to work, .NET‐specific versions of these languages have also appeared, and more are being released all the time. For a list of languages, see https://msdn.microsoft.com/en‐us/library/ee822860(v=vs.100).aspx. Not only do these languages have access to the .NET Framework, but they can also communicate with each other. It is possible for C# developers to make use of code written by Visual Basic programmers, and vice versa.

    All of this provides an extremely high level of versatility and is part of what makes using the .NET Framework such an attractive prospect.

    What's in the .NET Framework?

    The .NET Framework consists primarily of a gigantic library of code that you use from your client‐ or server‐side languages (such as C#) using object‐oriented programming (OOP) techniques. This library is categorized into different modules—you use portions of it depending on the results you want to achieve. For example, one module contains the building blocks for Windows applications, another for network programming, and another for web development. Some modules are divided into more specific submodules, such as a module for building web services within the module for web development.

    The intention is for different operating systems to support some or all of these modules, depending on their characteristics. A smartphone, for example, includes support for all the base .NET functionality, but is unlikely to require some of the more esoteric modules.

    Part of the .NET Framework library defines some basic types. A type is a representation of data, and specifying some of the most fundamental of these (such as a 32‐bit signed integer) facilitates interoperability between languages using the .NET Framework. This is called the Common Type System (CTS).

    As well as supplying this library, the .NET Framework also includes the .NET Common Language Runtime (CLR), which is responsible for the execution of all applications developed using the.NET library.

    .NET Standard and .NET Core

    When the .NET Framework was originally created, although it was designed for running on multiple platforms, there was no industry accepted open‐source forking concept. These days, usually on GitHub, a project can be forked and then customized to run on multiple platforms. For example, the .NET Compact Framework and the .NET Micro Framework are forks of the .NET Framework, like .NET Core, which was created as the most optimal solution for cross‐platform code development. Each of those .NET Framework flavors or verticals had a specific set of requirements and objectives that triggered the need to make that fork.

    Included in the .NET Framework is a set of Base Class Libraries (BCL) that contain APIs for basic actions most developers need a program to do. These actions include, for example, file access, string manipulation, managing streams, storing data in collections, security attributes, and many others. These fundamental capabilities are often implemented differently within each of the .NET Framework flavors. This requires a developer to learn, develop, and manage multiple BCLs for each fork or flavor of their application based on the platform it runs. This is the problem that the .NET Standard has solved.

    The expectation is that shortly, this forking concept will result in many more flavors of the .NET Framework. This increase will necessitate a standard set of basic programming APIs that works with each fork and flavor. Without this cross platform base library, the development and support complexities would prevent the speedy adoption of the forked version. In short, .NET Standard is a class library that exposes APIs that support any fork or flavor of application using the .NET Platform.

    Writing Applications Using the .NET Framework and .NET Core

    Writing an application using either the .NET Framework or .NET Core means writing code (using any of the languages that support the Framework) using the .NET code library. In this book you use Visual Studio for your development. Visual Studio is a powerful, integrated development environment that supports C# (as well as managed and unmanaged C++, Visual Basic, and some others). The advantage of this environment is the ease with which .NET features can be integrated into your code. The code that you create will be entirely C# but use the .NET Framework throughout, and you'll make use of the additional tools in Visual Studio where necessary.

    In order for C# code to execute, it must be converted into a language that the target operating ‐system understands, known as native code. This conversion is called compiling code, an act that is performed by a compiler. Under the .NET Framework and .NET Core, this is a two‐stage process.

    CIL and JIT

    When you compile code that uses either the .NET Framework or .NET Core library, you don't immediately create operating system–specific native code. Instead, you compile your code into Common Intermediate Language (CIL) code. This code isn't specific to any operating system (OS) and isn't specific to C#. Other .NET languages—Visual Basic .NET or F#, for example—also compile to this language as a first stage. This compilation step is carried out by Visual Studio when you develop C# applications.

    Obviously, more work is necessary to execute an application. That is the job of a just‐in‐time (JIT) compiler, which compiles CIL into native code that is specific to the OS and machine architecture being targeted. Only at this point can the OS execute the application. The just‐in‐time part of the name reflects the fact that CIL code is compiled only when it is needed. This compilation can happen on the fly while your application is running, although luckily this isn't something that you normally need to worry about as a developer. Unless you are writing extremely advanced code where performance is critical, it's enough to know that this compilation process will churn along merrily in the background, without interfering.

    In the past, it was often necessary to compile your code into several applications, each of which targeted a specific operating system and CPU architecture. Typically, this was a form of optimization (to get code to run faster on an AMD chipset, for example), but at times it was critical (for applications to work in both Win9x and WinNT/2000 environments, for example). This is now unnecessary because JIT compilers (as their name suggests) use CIL code, which is independent of the machine, operating system, and CPU. Several JIT compilers exist, each targeting a different architecture, and the CLR/CoreCLR uses the appropriate one to create the native code required.

    The beauty of all this is that it requires a lot less work on your part—in fact, you can forget about system‐dependent details and concentrate on the more interesting functionality of your code.

    NOTE

    As you learn about .NET you might come across references to Microsoft Intermediate Language (MSIL). MSIL was the original name for CIL, and many developers still use this terminology today. See https://en.wikipedia.org/wiki/Common_Intermediate_Language for more information about CIL.

    Assemblies

    When you compile an application, the CIL code is stored in an assembly. Assemblies include both executable application files that you can run directly from Windows without the need for any other programs (these have an .exe file extension) and libraries (which have a .dll extension) for use by other applications.

    In addition to containing CIL, assemblies also include meta information (that is, information about the information contained in the assembly, also known as metadata) and optional resources (additional data used by the CIL, such as sound files and pictures). The meta information enables assemblies to be fully self‐descriptive. You need no other information to use an assembly, meaning you avoid situations such as failing to add required data to the system registry and so on, which was often a problem when developing with other platforms.

    This means that deploying applications is often as simple as copying the files into a directory on a remote computer. Because no additional information is required on the target systems, you can just run an executable file from this directory and, assuming the .NET CLR is installed for .NET Framework targeted applications, you're good to go. For .NET Core targeted applications, all modules required to run the program are included in the deployment package and therefore no additional configurations are required.

    From a .NET Framework perspective, you won't necessarily want to include everything required to run an application in one place. You might write some code that performs tasks required by multiple applications. In situations like that, it is often useful to place the reusable code in a place accessible to all applications. In the .NET Framework, this is the global assembly cache (GAC). Placing code in the GAC is simple—you just place the assembly containing the code in the directory containing this cache.

    Managed Code

    The role of the CLR/CoreCLR doesn't end after you have compiled your code to CIL and a JIT compiler has compiled that to native code. Code written using the .NET Framework and .NET Core are managed when it is executed (a stage usually referred to as runtime). This means that the CLR/CoreCLR looks after your applications by managing memory, handling security, allowing cross‐language debugging, and so on. By contrast, applications that do not run under the control of the CLR/CoreCLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low‐level functions of the operating system. However, in C# you can write only code that runs in a managed environment. You will make use of the managed features of the CLR/CoreCLR and allow .NET itself to handle any interaction with the operating system.

    Garbage Collection

    One of the most important features of managed code is the concept of garbage collection. This is the .NET method of making sure that the memory used by an application is freed up completely when the application is no longer in use. Prior to .NET this was mostly the responsibility of programmers, and a few simple errors in code could result in large blocks of memory mysteriously disappearing as a result of being allocated to the wrong place in memory. That usually meant a progressive slowdown of your computer, followed by a system crash.

    .NET garbage collection works by periodically inspecting the memory of your computer and removing anything from it that is no longer needed. There is no set time frame for this; it might happen thousands of times a second, once every few seconds, or whenever, but you can rest assured that it will happen.

    There are some implications for programmers here. Because this work is done for you at an unpredictable time, applications have to be designed with this in mind. Code that requires a lot of memory to run should tidy itself up, rather than wait for garbage collection to happen, but that isn't as tricky as it sounds.

    Fitting It Together

    Before moving on, let's summarize the steps required to create a .NET application as discussed previously:

    Application code is written using a .NET‐compatible language such as C# (see Figure 1‐1).

    That code is compiled into CIL, which is stored in an assembly (see Figure 1‐2).

    When this code is executed (either in its own right if it is an executable or when it is used from other code), it must first be compiled into native code using a JIT compiler (see Figure 1‐3).

    The native code is executed in the context of the managed CLR/CoreCLR, along with any other running applications or processes, as shown in Figure 1‐4.

    Diagrammatic illustration of an application code written using a .NET-compatible language such as C#.

    FIGURE 1‐1

    Diagrammatic illustration of C# application code compiled into CIL, which is stored in an assembly.

    FIGURE 1‐2

    Diagrammatic illustration of a code which is compiled into native code using a JIT compilation.

    FIGURE 1‐3

    Diagrammatic illustration of a native code executed in the context of a managed CLR/CoreCLR (common language runtime).

    FIGURE 1‐4

    Linking

    Note one additional point concerning this process. The C# code that compiles into CIL in step 2 needn't be contained in a single file. It's possible to split application code across multiple source‐code files, which are then compiled together into a single assembly. This extremely useful process is known as linking. It is required because it is far easier to work with several smaller files than one enormous one. You can separate logically related code into an individual file so that it can be worked on independently and then practically forgotten about when completed. This also makes it easy to locate specific pieces of code when you need them and enables teams of developers to divide the programming burden into manageable chunks, whereby individuals can check out pieces of code to work on without risking damage to otherwise satisfactory sections or sections other people are working on.

    WHAT IS C#?

    C#, as mentioned earlier, is one of the languages you can use to create applications that will run in the .NET CLR/CoreCLR. It is an evolution of the C and C++ languages and has been created by Microsoft specifically to work with the .NET platform. The C# language has been designed to incorporate many of the best features from other languages, while clearing up their problems.

    Developing applications using C# is simpler than using C++ because the language syntax is simpler. Still, C# is a powerful language, and there is little you might want to do in C++ that you can't do in C#. Having said that, those features of C# that parallel the more advanced features of C++, such as directly accessing and manipulating system memory, can be carried out only by using code marked as unsafe. This advanced programmatic technique is potentially dangerous (hence its name) because it is possible to overwrite system‐critical blocks of memory with potentially catastrophic results. For this reason, and others, this book does not cover that topic.

    At times, C# code is slightly more verbose than C++. This is a consequence of C# being a typesafe language (unlike C++). In layperson's terms, this means that once some data has been assigned to a type, it cannot subsequently transform itself into another unrelated type. Consequently, strict rules must be adhered to when converting between types, which means you will often need to write more code to carry out the same task in C# than you might write in C++. However, there are benefits to this—the code is more robust, debugging is simpler, and .NET can always track the type of a piece of data at any time. In C#, you therefore might not be able to do things such as take the region of memory 4 bytes into this data and 10 bytes long and interpret it as X, but that's not necessarily a bad thing.

    C# is just one of the languages available for .NET development, but it is certainly the best. It has the advantage of being the only language designed from the ground up for the .NET Framework and is the principal language used in versions of .NET that are ported to other operating systems. To keep languages such as the .NET version of Visual Basic as similar as possible to their predecessors yet compliant with the CLR/CoreCLR, certain features of the .NET code library are not fully supported, or at least require unusual syntax.

    By contrast, C# can make use of every feature that the .NET Framework code library has to offer, but not all features have been ported to .NET Core. Also, each new version of .NET has included additions to the C# language, partly in response to requests from developers, making it even more powerful.

    Applications You Can Write with C#

    The .NET Framework has no restrictions on the types of applications that are possible, as discussed earlier. C# uses the framework and therefore has no restrictions on possible applications. (However, currently it is possible to write only Console and ASP.NET applications using .NET Core.) However, here are a few of the more common application types:

    Desktop applications—Applications, such as Microsoft Office, that have a familiar Windows look and feel about them. This is made simple by using the Windows Presentation Foundation (WPF) module of the .NET Framework, which is a library of controls (such as buttons, toolbars, menus, and so on) that you can use to build a Windows user interface (UI).

    Windows Store applications—Windows 8 introduced a new type of application, known as a Windows Store application. This type of application is designed primarily for touch devices, and it is usually run full‐screen, with a minimum of clutter, and an emphasis on simplicity. You can create these applications in several ways, including using WPF.

    Cloud/Web applications—The .NET Framework and .NET Core include a powerful system named ASP.NET, for generating web content dynamically, enabling personalization, security, and much more. Additionally, these applications can be hosted and accessed in the Cloud, for example on the Microsoft Azure platform.

    Web APIs—An ideal framework for building RESTful HTTP services that support a broad variety of clients, including mobile devices and browsers.

    WCF services—A way to create versatile distributed applications. Using WCF you can exchange virtually any data over local networks or the Internet, using the same simple syntax regardless of the language used to create a service or the system on which it resides.

    Any of these types might also require some form of database access, which can be achieved using the ADO.NET (Active Data Objects .NET) section of the .NET Framework, through the Entity Framework, or through the LINQ (Language Integrated Query) capabilities of C#. For .NET Core applications requiring database access you would use the Entity Framework Core library. Many other resources can be drawn on, such as tools for creating networking components, outputting graphics, performing complex mathematical tasks, and so on.

    C# in this Book

    The first part of this book deals with the syntax and usage of the C# language without too much emphasis on the .NET Framework or .NET Core. This is necessary because you can't use either the .NET Framework or .NET Core at all without a firm grounding in C# programming. You'll start off even simpler, in fact, and leave the more involved topic of OOP until you've covered the basics. These are taught from first principles, assuming no programming knowledge at all.

    After that, you'll be ready to move on to developing more complex (but more useful) applications. Part II tackles Windows programming, Part III explores cloud and cross‐platform programming, and Part IV examines data access (for ORM database concepts, filesystem, and XML data) and LINQ. Part V of this book looks at WCF and Windows Store application programming.

    VISUAL STUDIO 2017

    In this book, you use the Visual Studio 2017 development tool for all of your C# programming, from simple command‐line applications to more complex project types. A development tool, or integrated development environment (IDE), such as Visual Studio isn't essential for developing C# applications, but it makes things much easier. You can (if you want to) manipulate C# source code files in a basic text editor, such as the ubiquitous Notepad application, and compile code into assemblies using the command‐line compiler that is part of the .NET Framework and .NET Core. However, why do this when you have the power of an IDE to help you?

    Visual Studio 2017 Products

    Microsoft supplies several versions of Visual Studio, for example:

    Visual Studio Code

    Visual Studio Community

    Visual Studio Professional

    Visual Studio Enterprise

    Visual Studio Code and Community are freely available at https://www.visualstudio.com/en‐us/downloads/download‐visual‐studio‐vs. The Professional and Enterprise version have additional capabilities, which carry a cost.

    The various Visual Studio products enable you to create almost any C# application you might need. Visual Studio Code is a simple yet robust code editor that runs on Windows, Linux, and iOS. Visual Studio Community, unlike Visual Studio Code, retains the same look and feel as Visual Studio Professional and Enterprise. Microsoft offers many of the same features in Visual Studio Community as exist in the Professional and Enterprise version; however, some notable features are absent, like deep debugging capabilities and code optimization tools. However, not so many features are absent that you can't use Community to work through the chapters of this book. Visual Studio Community 2017 is the version of the IDE used to work the examples in this book.

    Solutions

    When you use Visual Studio to develop applications, you do so by creating solutions. A solution, in Visual Studio terms, is more than just an application. Solutions contain projects, which might be WPF projects, Cloud/Web Application projects, ASP.NET Core projects, and so on. Because solutions can contain multiple projects, you can group together related code in one place, even if it will eventually compile to multiple assemblies in various places on your hard disk.

    This is very useful because it enables you to work on shared code (which might be placed in the GAC) at the same time as applications that use this code. Debugging code is a lot easier when only one development environment is used because you can step through instructions in multiple code modules.

    WHAT YOU LEARNED IN THIS CHAPTER

    2

    Writing a C# Program

    WHAT YOU WILL LEARN IN THIS CHAPTER

    Understanding Visual Studio 2017 basics

    Writing a simple console application

    Writing a simple desktop application

    WROX.COM CODE DOWNLOADS FOR THIS CHAPTERS

    The wrox.com code downloads for this chapter are found on this book's webpage on Wrox.com on the Download Code tab. The code can also be found at http://github.com/benperk/BeginningCSharp7. The code is in the Chapter02 folder and individually named according to the names throughout the chapter.

    Now that you've spent some time learning what C# is and how it fits into the .NET Framework, it's time to get your hands dirty and write some code. You use Visual Studio Community 2017 (VS) throughout this book, so the first thing to do is have a look at some of the basics of this development environment.

    Visual Studio is an enormous and complicated product, and it can be daunting to first‐time users, but using it to create basic applications can be surprisingly simple. As you start to use Visual Studio in this chapter, you will see that you don't need to know a huge amount about it to begin playing with C# code. Later in the book you'll see some of the more complicated operations that Visual Studio can perform, but for now a basic working knowledge is all that is required.

    After you've looked at the IDE, you put together two simple applications. You don't need to worry too much about the code in these applications for now; you just want to prove that things work. By working through the application‐creation procedures in these early examples, they will become second nature before too long.

    You will learn how to create two basic types of applications in this chapter: a console application and a desktop application.

    The first application you create is a simple console application. Console applications don't use the graphical windows environment, so you won't have to worry about buttons, menus, interaction with the mouse pointer, and so on. Instead, you run the application in a command prompt window and interact with it in a much simpler way.

    The second application is a desktop application, which you create using Windows Presentation Foundation (WPF). The look and feel of a desktop application is very familiar to Windows users, and (surprisingly) the application doesn't require much more effort to create. However, the syntax of the code required is more complicated, even though in many cases you don't have to worry about details.

    You use both types of application in Part II, Part III, and Part IV of the book, with more emphasis on console applications at the beginning. The additional flexibility of desktop applications isn't necessary when you are learning the C# language, while the simplicity of console applications enables you to concentrate on learning the syntax without worrying about the look and feel of the application.

    THE VISUAL STUDIO 2017 DEVELOPMENT ENVIRONMENT

    When you begin the installation of Visual Studio Community 2017 you are prompted with a window similar to Figure 2‐1. It provides a list of Workloads, Individual components, and Language packs to install along with the core editor.

    Install the following Workloads and click the Install button.

    Windows—Universal Windows Platform development

    Windows—.Net desktop development

    .NET Framework 4.7 development tools

    Web & Cloud—ASP.NET and web development

    Web & Cloud—Azure development

    Other Toolsets—.NET Core cross‐platform development

    After installation is complete, when Visual Studio is first loaded, it immediately presents you with the option to Sign in to Visual Studio using your Microsoft Account. By doing this, your Visual Studio settings are synced between devices so that you do not have to configure the IDE when using it on multiple workstations. If you do not have a Microsoft Account, follow the process for the creation of one and then use it to sign in. If you do not want to sign in, click the Not now, maybe later link, and continue the initial configuration of Visual Studio. We recommend that at some point you sign in and get a developer license.

    Screenshot illustration of an installation of Visual Studio Community 2017 with a window.

    FIGURE 2‐1

    If this is the first time you've run Visual Studio, you will be presented with a list of preferences intended for users who have experience with previous releases of this development environment. The choices you make here affect a number of things, such as the layout of windows, the way that console windows run, and so on. Therefore, choose Visual C# from the drop‐down; otherwise, you might find that things don't quite work as described in this book. Note that the options available vary depending on the options you chose when installing Visual Studio, but as long as you chose to install C# this option will be available.

    If this isn't the first time that you've run Visual Studio, and you chose a different option the first time, don't panic. To reset the settings to Visual C#, you simply have to import them. To do this, select Tools Import and Export Settings, and choose the Reset All Settings option, shown in Figure 2‐2.

    Click Next, and indicate whether you want to save your existing settings before proceeding. If you have customized things, you might want to do this; otherwise, select No and click Next again. From the next dialog box, select Visual C#, shown in Figure 2‐3. Again, the available options may vary.

    Screenshot illustration of how to run Visual Studio by selecting Tools➪ Import and Export Settings, and choose the Reset All Settings option.

    FIGURE 2‐2

    Screenshot illustration of how to save the existing settings before proceeding to select Visual C#.

    FIGURE 2‐3

    Finally, click Finish, then Close to apply the settings.

    The Visual Studio environment layout is completely customizable, but the default is fine here. With C# Developer Settings selected, it is arranged as shown in Figure 2‐4.

    Screenshot illustration of the arrangement of the Visual Studio environment layout.

    FIGURE 2‐4

    The main window, which contains a helpful Start Page by default when Visual Studio is started, is where all your code is displayed. This window can contain many documents, each indicated by a tab, so you can easily switch between several files by clicking their filenames. It also has other functions: It can display GUIs that you are designing for your projects, plain‐text files, HTML, and various tools that are built into Visual Studio. You will come across all of these in the course of this book.

    Above the main window are toolbars and the Visual Studio menu. Several different toolbars can be placed here, with functionality ranging from saving and loading files to building and running projects to debugging controls. Again, you are introduced to these as you need to use them.

    Here are brief descriptions of each of the main features that you will use the most:

    The Toolbox window pops up when you click its tab. It provides access to, among other things, the user interface building blocks for desktop applications. Another tab, Server Explorer, can also appear here (selectable via the View Server Explorer menu option) and includes various additional capabilities, such as Azure subscription details, providing access to data sources, server settings, services, and more.

    The Solution Explorer window displays information about the currently loaded solution. A solution, as you learned in the previous chapter, is Visual Studio terminology for one or more projects along with their configurations. The Solution Explorer window displays various views of the projects in a solution, such as what files they contain and what is contained in those files.

    The Team Explorer window displays information about the current Team Foundation Server or Team Foundation Service connection. This allows you access to source control, bug tracking, build automation, and other functionality. However, this is an advanced subject and is not covered in this book.

    Just below the Solution Explorer window you can display a Properties window, not shown in Figure 2‐4 because it appears only when you are working on a project (you can also toggle its display using View Properties Window). This window provides a more detailed view of the project's contents, enabling you to perform additional configuration of individual elements. For example, you can use this window to change the appearance of a button in a desktop application.

    Also not shown in the screenshot is another extremely important window: the Error List window, which you can display using View Error List. It shows errors, warnings, and other project‐related information. The window updates continuously, although some information appears only when a project is compiled.

    This might seem like a lot to take in, but it doesn't take long to get comfortable. You start by building the first of your example projects, which involves many of the Visual Studio elements just described.

    NOTE

    Visual Studio is capable of displaying many other windows, both informational and functional. Many of these can share screen space with the windows mentioned here, and you can switch between them using tabs, dock them elsewhere, or even detach them and place them on other displays if you have multiple monitors. Several of these windows are used later in the book, and you'll probably discover more yourself when you explore the Visual Studio environment in more detail.

    CONSOLE APPLICATIONS

    You use console applications regularly in this book, particularly at the beginning, so the following Try It Out provides a step‐by‐step guide to creating a simple one.

    TRY IT OUT Creating a Simple Console Application: ConsoleApplication1\Program.cs

    Create a new console application project by selecting File New Project, as shown in Figure 2‐5.

    Ensure that the Visual C# node is selected in the left pane of the window that appears, and choose the Console Application (.NET Framework) project type in the middle pane (see Figure 2‐6). Change the Location text box to C:\BeginningCSharp7\Chapter02 (this directory is created automatically if it doesn't already exist). Leave the default text in the Name text box (ConsoleApplication1) and the other settings as they are (refer to Figure 2‐6).

    Click the OK button.

    Once the project is initialized, add the following lines of code to the file displayed in the main window:

    namespace ConsoleApplication1{  class Program  {      static void Main(string[] args)      {// Output text to the screen.Console.WriteLine(The first app in Beginning Visual C# 2017!);Console.ReadKey();      }  }}

    Select the Debug Start Debugging menu item. After a few moments you should see the window shown in Figure 2‐7.

    Press any key to exit the application (you might need to click on the console window to focus on it first). The display in Figure 2‐7 appears only if the Visual C# Developer Settings are applied, as described earlier in this chapter. For example, with Visual Basic Developer Settings applied, an empty console window is displayed, and the application output appears in a window labeled Immediate. In this case, the Console.ReadKey() code also fails, and you see an error. If you experience this problem, the best solution for working through the examples in this book is to apply the Visual C# Developer Settings—that way, the results you see match the results shown here.

    Screenshot illustration of creating a new console application project by selecting File➪ New➪ Project.

    FIGURE 2‐5

    Screenshot illustration of choosing the Console Application (.NET Framework) project type in the middle pane.

    FIGURE 2‐6

    Screenshot illustration of the Window page seen after selecting the Debug➪ Start Debugging menu item.

    FIGURE 2‐7

    How It Works

    For now, I won't dissect the code used thus far because the focus here is on how to use the development tools to get code up and running. Clearly, Visual Studio does a lot of the work for you and makes the process of compiling and executing code simple. In fact, there are multiple ways to perform even these basic steps—for instance, you can create a new project by using the menu item mentioned earlier, by pressing Ctrl+Shift+N, or by clicking the corresponding icon in the toolbar.

    Similarly, your code can be compiled and executed in several ways. The process you used in the example—selecting Debug Start Debugging—also has a keyboard shortcut (F5) and a toolbar icon. You can also run code without being in debugging mode using the Debug Start Without Debugging menu item (or by pressing Ctrl+F5), or compile your project without running it (with debugging on or off) using Build Build Solution or pressing F6. Note that you can execute a project without debugging or build a project using toolbar icons, although these icons don't appear on the toolbar by default. After you have compiled your code, you can also execute it simply by running the .exe file produced in Windows Explorer, or from the command prompt. To do this, open a command prompt window, change the directory to C:\ BeginningCSharp7\Chapter02\ConsoleApplication1\ConsoleApplication1\bin\Debug\, type ConsoleApplication1, and press Enter.

    NOTE

    In future examples, when you see the instructions create a new console project or execute the code, you can choose whichever method you want to perform these steps. Unless otherwise stated, all code should be run with debugging enabled. In addition, the terms start, execute, and run are used interchangeably in this book, and discussions following examples always assume that you have exited the application in the example.

    Console applications terminate as soon as they finish execution, which can mean that you don't get a chance to see the results if you run them directly through the IDE. To get around this in the preceding example, the code is told to wait for a key press before terminating, using the following line:

      Console.ReadKey();

    You will see this technique used many times in later examples. Now that you've created a project, you can take a more detailed look at some of the regions of the development environment.

    The Solution Explorer

    By default, the Solution Explorer window is docked in the top‐right corner of the screen. As with other windows, you can move it wherever you like, or you can set it to auto‐hide by clicking the pin icon. The Solution Explorer window shares space with another useful window called Class View, which you can display using View Class View. Figure 2‐8 shows both of these windows with all nodes expanded (you can toggle between them by clicking on the tabs at the bottom of the window when the window is docked).

    Screenshot illustration of both the Solution Explorer window and another useful window called Class View, with all nodes expanded.

    FIGURE 2‐8

    This Solution Explorer view shows the files that make up the ConsoleApplication1 project. The file to which you added code, Program.cs, is shown along with another code file, AssemblyInfo.cs, and several references.

    NOTE

    All C# code files have a .cs file extension.

    You don't have to worry about the AssemblyInfo.cs file for the moment. It contains extra information about your project that doesn't concern you yet.

    You can use this window to change what code is displayed in the main window by double‐clicking .cs files; right‐clicking them and selecting View Code; or by selecting them and clicking the toolbar button that appears at the top of the window. You can also perform other operations on files here, such as renaming them or deleting them from your project. Other file types can also appear here, such as project resources (resources are files used by the project that might not be C# files, such as bitmap images and sound files). Again, you can manipulate them through the same interface.

    You can also expand code items such as Program.cs to see what is contained. This overview of your code structure can be a very useful tool; it also enables you to navigate directly to specific parts of your code file, instead of opening the code file and scrolling to the part you want.

    The References entry contains a list of the .NET libraries you are using in your project. You'll look at this later; the standard references are fine for now. Class View presents an alternative view of your project by showing the structure of the code you created. You'll come back to this later in the book; for now the Solution Explorer display is appropriate. As you click on files or other icons in these windows, notice that the contents of the Properties window (shown in Figure 2‐9) changes.

    Screenshot illustration showing the contents of the Properties window, as one clicks on files or other icons in the 2 windows.

    FIGURE 2‐9

    The Properties Window

    The Properties window (select View Properties Window if it isn't already displayed) shows additional information about whatever you select

    Enjoying the preview?
    Page 1 of 1