Introduction

Microsoft Visual C# is a powerful but simple language aimed primarily at developers who create applications built on the Microsoft .NET Framework. Visual C# inherits many of the best features of C++ and Microsoft Visual Basic but few of the inconsistencies and anachronisms, which results in a cleaner and more logical language.

  • C# 1.0 made its public debut in 2001.

  • C# 2.0, with Visual Studio 2005, provided several important new features, including generics, iterators, and anonymous methods.

  • C# 3.0, which was released with Visual Studio 2008, added extension methods, lambda expressions, and most famously of all, the Language-Integrated Query facility, or LINQ.

  • C# 4.0 was released in 2010 and provided further enhancements that improved its interoperability with other languages and technologies. These features included support for named and optional arguments and the dynamic type, which indicates that the language runtime should implement late binding for an object. An important addition to the .NET Framework, and released concurrently with C# 4.0, were the classes and types that constitute the Task Parallel Library (TPL). Using the TPL, you can build highly scalable applications that can take full advantage of multicore processors.

  • C# 5.0 added native support for asynchronous task-based processing through the async method modifier and the await operator.

  • C# 6.0 was an incremental upgrade with features designed to make life simpler for developers. These features include items such as string interpolation (you need never use String.Format again!), enhancements to the ways in which properties are implemented, expression-bodied methods, and others.

  • C# 7.0 adds further enhancements to aid productivity and remove some of the minor anachronisms of C#. For example, you can now implement property accessors as expression-bodied members, methods can return multiple values in the form of tuples, the use of out parameters has been simplified, and switch statements have been extended to support pattern- and type-matching. There are other updates as well, which are covered in this book.

It goes without saying that Microsoft Windows 10 is an important platform for running C# applications, but now you can also run code developed by using C# on other operating systems, such as Linux, through the .NET Core runtime. This opens up possibilities for writing code that can run in multiple environments. Additionally, Windows 10 supports highly interactive applications that can share data and collaborate as well as connect to services running in the cloud. The key notion in Windows 10 is Universal Windows Platform (UWP) apps—applications designed to run on any Windows 10 device, whether a fully fledged desktop system, a laptop, a tablet, or even an IoT (Internet of Things) device with limited resources. Once you have mastered the core features of C#, gaining the skills to build applications that can run on all these platforms is important.

Voice activation is another feature that has come to the fore, and Windows 10 includes Cortana, your personal voice-activated digital assistant. You can integrate your own apps with Cortana to allow them to participate in data searches and other operations. Despite the complexity normally associated with natural-language speech analysis, enabling your apps to respond to Cortana’s requests is surprisingly easy; I cover this in Chapter 26. Also, the cloud has become such an important element in the architecture of many systems—ranging from large-scale enterprise applications to mobile apps running on portable devices—that I decided to focus on this aspect of development in the final chapter of the book.

The development environment provided by Visual Studio 2017 makes these features easy to use, and the many new wizards and enhancements included in the latest version of Visual Studio can greatly improve your productivity as a developer. I hope you have as much fun working through this book as I had writing it!

Who should read this book

This book assumes that you are a developer who wants to learn the fundamentals of programming with C# by using Visual Studio 2017 and the .NET Framework version 4.6.1. By the time you complete this book, you will have a thorough understanding of C# and will have used it to build responsive and scalable applications that can run on the Windows 10 operating system.

Who should not read this book

This book is aimed at developers new to C# but not completely new to programming. As such, it concentrates primarily on the C# language. This book is not intended to provide detailed coverage of the multitude of technologies available for building enterprise-level and global applications for Windows, such as ADO.NET, ASP.NET, Azure, or Windows Communication Foundation. If you require more information on any of these items, you might consider reading some of the other titles available from Microsoft Press.

Organization of this book

This book is divided into four sections:

  • Part I, “Introducing Microsoft Visual C# and Microsoft Visual Studio 2017,” provides an introduction to the core syntax of the C# language and the Visual Studio programming environment.

  • Part II, “Understanding the C# object model,” goes into detail on how to create and manage new types in C# and how to manage the resources referenced by these types.

  • Part III, “Defining extensible types with C#,” includes extended coverage of the elements that C# provides for building types that you can reuse across multiple applications.

  • Part IV, “Building Universal Windows Platform applications with C#,” describes the universal Windows 10 programming model and how you can use C# to build interactive applications for this model.

Finding your best starting point in this book

This book is designed to help you build skills in a number of essential areas. You can use this book if you are new to programming or if you are switching from another programming language such as C, C++, Java, or Visual Basic. Use the following table to find your best starting point.

If you are

Follow these steps

New to object-oriented programming

1. Install the practice files as described in the upcoming section, “Code samples.”

2. Work through the chapters in Parts I, II, and III sequentially.

3. Complete Part IV as your level of experience and interest dictates.

Familiar with procedural programming languages, such as C, but new to C#

1. Install the practice files as described in the upcoming section, “Code samples.”

2. Skim the first five chapters to get an overview of C# and Visual Studio 2017, and then concentrate on Chapters 6 through 22.

3. Complete Part IV as your level of experience and interest dictates.

Migrating from an object-oriented language such as C++ or Java

1. Install the practice files as described in the upcoming section, “Code samples.”

2. Skim the first seven chapters to get an overview of C# and Visual Studio 2017, and then concentrate on Chapters 8 through 22.

3. For information about building Universal Windows Platform applications, read Part IV.

Switching from Visual Basic to C#

1. Install the practice files as described in the upcoming section, “Code samples.”

2. Work through the chapters in Parts I, II, and III sequentially.

3. For information about building Universal Windows Platform applications, read Part IV.

4. Read the Quick Reference sections at the end of the chapters for information about specific C# and Visual Studio 2017 constructs.

Referencing the book after working through the exercises

1. Use the index or the table of contents to find information about particular subjects.

2. Read the Quick Reference sections at the end of each chapter to find a brief review of the syntax and techniques presented in the chapter.

Most of the book’s chapters include hands-on samples that let you try out the concepts you just learned. No matter which sections you choose to focus on, be sure to download and install the sample applications on your system.

Conventions and features in this book

This book presents information by using conventions designed to make the information readable and easy to follow.

  • Each exercise consists of a series of tasks, presented as numbered steps (1, 2, and so on) listing each action you must take to complete the exercise.

  • Boxed elements with labels such as “Note” provide additional information or alternative methods for completing a step successfully.

  • Text that you type (apart from code blocks) appears in bold.

  • A plus sign (+) between two key names means that you must press those keys at the same time. For example, “Press Alt+Tab” means that you hold down the Alt key while you press the Tab key.

System requirements

You will need the following hardware and software to complete the practice exercises in this book:

  • Windows 10 (Home, Professional, Education, or Enterprise) version 1507 or higher.

  • The most recent build of Visual Studio Community 2017, Visual Studio Professional 2017, or Visual Studio Enterprise 2017 (make sure that you have installed any updates). As a minimum, you should select the following workloads when installing Visual Studio 2017:

• Universal Windows Platform development

• .NET desktop development

• ASP.NET and web development

• Azure development

• Data storage and processing

• .NET Core cross-platform development

Images

Note All the exercises and code samples in this book have been developed and tested using Visual Studio Community 2017. They should all work, unchanged, in Visual Studio Professional 2017 and Visual Studio Enterprise 2017.

  • A computer that has a 1.8 GHz or faster processor (dual-core or better recommended)

  • 2 GB RAM (4 GB RAM recommended, add 512 MB if running in a virtual machine)

  • 10 GB of available hard disk space after installing Visual Studio

  • 5400 RPM hard-disk drive (SSD recommended)

  • A video card that supports a 1024 × 768 or higher resolution display

  • Internet connection to download software or chapter examples

Depending on your Windows configuration, you might require local Administrator rights to install or configure Visual Studio 2017.

You also need to enable developer mode on your computer to be able to create and run UWP apps. For details on how to do this, see “Enable Your Device for Development,” at https://msdn.microsoft.com/library/windows/apps/dn706236.aspx.

Code samples

Most of the chapters in this book include exercises with which you can interactively try out new material learned in the main text. You can download all the sample projects, in both their pre-exercise and post-exercise formats, from the following page:

https://aka.ms/VisCSharp9e/downloads

Images

Note In addition to the code samples, your system should have Visual Studio 2017 installed. If available, install the latest service packs for Windows and Visual Studio.

Installing the code samples

Follow these steps to install the code samples on your computer so that you can use them with the exercises in this book:

  1. Unzip the CSharpSBS.zip file that you downloaded from the book’s website, extracting the files into your Documents folder.

  2. If prompted, review the end-user license agreement. If you accept the terms, select the Accept option and then click Next.

Images

Note If the license agreement doesn’t appear, you can access it from the same webpage from which you downloaded the CSharpSBS.zip file.

Using the code samples

Each chapter in this book explains when and how to use the code samples for that chapter. When it’s time to use a code sample, the book will list the instructions for how to open the files.

Images

Important Many of the code samples depend on NuGet packages that are not included with the code. These packages are downloaded automatically the first time you build a project. As a result, if you open a project and examine the code before doing a build, Visual Studio might report a large number of errors for unresolved references. Building the project will resolve these references, and the errors should disappear.

For those of you who like to know all the details, here’s a list of the sample Visual Studio 2017 projects and solutions, grouped by the folders in which you can find them. In many cases, the exercises provide starter files and completed versions of the same projects that you can use as a reference. The completed projects for each chapter are stored in folders with the suffix “- Complete.”

Project/Solution

Description

Chapter 1

TextHello

This project gets you started. It steps through the creation of a simple program that displays a text-based greeting.

Hello

This project opens a window that prompts the user for his or her name and then displays a greeting.

Chapter 2

PrimitiveDataTypes

This project demonstrates how to declare variables by using each of the primitive types, how to assign values to these variables, and how to display their values in a window.

MathsOperators

This program introduces the arithmetic operators (+ – * / %).

Chapter 3

Methods

In this project, you’ll reexamine the code in the MathsOperators project and investigate how it uses methods to structure the code.

DailyRate

This project walks you through writing your own methods, running the methods, and stepping through the method calls by using the Visual Studio 2015 debugger.

DailyRate Using Optional Parameters

This project shows you how to define a method that takes optional parameters and call the method by using named arguments.

Chapter 4

Selection

This project shows you how to use a cascading if statement to implement complex logic, such as comparing the equivalence of two dates.

SwitchStatement

This simple program uses a switch statement to convert characters into their XML representations.

Chapter 5

WhileStatement

This project demonstrates a while statement that reads the contents of a source file one line at a time and displays each line in a text box on a form.

DoStatement

This project uses a do statement to convert a decimal number to its octal representation.

Chapter 6

MathsOperators

This project revisits the MathsOperators project from Chapter 2 and shows how various unhandled exceptions can make the program fail. The try and catch keywords then make the application more robust so that it no longer fails.

Chapter 7

Classes

This project covers the basics of defining your own classes, complete with public constructors, methods, and private fields. It also shows how to create class instances by using the new keyword and how to define static methods and fields.

Chapter 8

Parameters

This program investigates the difference between value parameters and reference parameters. It demonstrates how to use the ref and out keywords.

Chapter 9

StructsAndEnums

This project defines a struct type to represent a calendar date.

Chapter 10

Cards

This project shows how to use arrays to model hands of cards in a card game.

Chapter 11

ParamsArray

This project demonstrates how to use the params keyword to create a single method that can accept any number of int arguments.

Chapter 12

Vehicles

This project creates a simple hierarchy of vehicle classes by using inheritance. It also demonstrates how to define a virtual method.

ExtensionMethod

This project shows how to create an extension method for the int type, providing a method that converts an integer value from base 10 to a different number base.

Chapter 13

Drawing

This project implements part of a graphical drawing package. The project uses interfaces to define the methods that drawing shapes expose and implement.

Chapter 14

GarbageCollectionDemo

This project shows how to implement exception-safe disposal of resources by using the Dispose pattern.

Chapter 15

Drawing Using Properties

This project extends the application in the Drawing project developed in Chapter 13 to encapsulate data in a class by using properties.

AutomaticProperties

This project shows how to create automatic properties for a class and use them to initialize instances of the class.

Chapter 16

Indexers

This project uses two indexers: one to look up a person’s phone number when given a name and the other to look up a person’s name when given a phone number.

Chapter 17

BinaryTree

This solution shows you how to use generics to build a type-safe structure that can contain elements of any type.

BuildTree

This project demonstrates how to use generics to implement a type-safe method that can take parameters of any type.

Chapter 18

Cards

This project updates the code from Chapter 10 to show how to use collections to model hands of cards in a card game.

Chapter 19

BinaryTree

This project shows you how to implement the generic IEnumerator<T> interface to create an enumerator for the generic Tree class.

IteratorBinaryTree

This solution uses an iterator to generate an enumerator for the generic Tree class.

Chapter 20

Delegates

This project shows how to decouple a method from the application logic that invokes it by using a delegate. The project is then extended to show how to use an event to alert an object to a significant occurrence, and how to catch an event and perform any processing required.

Chapter 21

QueryBinaryTree

This project shows how to use LINQ queries to retrieve data from a binary tree object.

Chapter 22

ComplexNumbers

This project defines a new type that models complex numbers and implements common operators for this type.

Chapter 23

GraphDemo

This project generates and displays a complex graph on a UWP form. It uses a single thread to perform the calculations.

Parallel GraphDemo

This version of the GraphDemo project uses the Parallel class to abstract out the process of creating and managing tasks.

GraphDemo With Cancellation

This project shows how to implement cancellation to halt tasks in a controlled manner before they have completed.

ParallelLoop

This application provides an example showing when you should not use the Parallel class to create and run tasks.

Chapter 24

GraphDemo

This is a version of the GraphDemo project from Chapter 23 that uses the async keyword and the await operator to perform the calculations that generate the graph data asynchronously.

PLINQ

This project shows some examples of using PLINQ to query data by using parallel tasks.

CalculatePI

This project uses a statistical sampling algorithm to calculate an approximation for pi. It uses parallel tasks.

Chapter 25

Customers

This project implements a scalable user interface that can adapt to different device layouts and form factors. The user interface applies XAML styling to change the fonts and background image displayed by the application.

Chapter 26

DataBinding

This is a version of the Customers project that uses data binding to display customer information retrieved from a data source in the user interface. It also shows how to implement the INotifyPropertyChanged interface so that the user interface can update customer information and send these changes back to the data source.

ViewModel

This version of the Customers project separates the user interface from the logic that accesses the data source by implementing the Model-View-ViewModel pattern.

Cortana

This project integrates the Customers app with Cortana. A user can issue voice commands to search for customers by name.

Chapter 27

Web Service

This solution includes a web application that provides an ASP.NET Web API web service that the Customers application uses to retrieve customer data from a SQL Server database. The web service uses an entity model created with the Entity Framework to access the database.

Errata and book support

We’ve made every effort to ensure the accuracy of this book and its companion content. Any errors that have been reported since this book was published are listed on our Microsoft Press site at:

https://aka.ms/VisCSharp9e/errata

If you find an error that is not already listed, you can report it to us through the same page.

If you need additional support, email Microsoft Press Book Support at [email protected].

Please note that product support for Microsoft software and hardware is not offered through the previous addresses. For help with Microsoft software or hardware, go to https://support.microsoft.com.

Stay in touch

Let’s keep the conversation going! We’re on Twitter: http://twitter.com/MicrosoftPress

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.119.148