C# 7 and .NET Core Cookbook - Dirk Strauss - E-Book

C# 7 and .NET Core Cookbook E-Book

Dirk Strauss

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

C# has recently been open-sourced and C# 7 comes with a host of new features for building powerful, cross-platform applications.
This book will be your solution to some common programming problems that you come across with C# and will also help you get started with .NET Core 1.1. Through a recipe-based approach, this book will help you overcome common programming challenges and get your applications ready to face the modern world.
We start by running you through new features in C# 7, such as tuples, pattern matching, and so on, giving you hands-on experience with them. Moving forward, you will work with generics and the OOP features in C#. You will then move on to more advanced topics, such as reactive extensions, Regex, code analyzers, and asynchronous programming. This book will also cover new, cross-platform .NET Core 1.1 features and teach you how to utilize .NET Core on macOS. Then, we will explore microservices as well as serverless computing and how these benefit modern developers. Finally, you will learn what you can do with Visual Studio 2017 to put mobile application development across multiple platforms within the reach of any developer.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 420

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Title Page

C# 7 and .NET Core Cookbook
Quick solutions to common programming problems with the latest features of C# 7.0, .NET Core 1.1, and Visual Studio 2017
Dirk Strauss

BIRMINGHAM - MUMBAI

Copyright

C# 7 and .NET Core Cookbook

Copyright © 2017 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: April 2017

Production reference: 1210417

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78728-627-6

www.packtpub.com

Credits

Author

Dirk Strauss

Copy Editor

Charlotte Carneiro

Reviewer

Fabio Claudio Ferracchiati

Project Coordinator

Ulhas Kambali

Commissioning Editor

Merint Thomas Mathew

Proofreader

Safis Editing

Acquisition Editor

Nitin Dasan

Indexer

Tejal Daruwale Soni

Content Development Editor

Vikas Tiwari

Production Coordinator

Shantanu N. Zagade

Technical Editor

Madhunikita Chindarkar

Foreword

When the author of this book, Dirk Strauss, asked me if I'd write a foreword, it took me about n milliseconds (where n is a small integer) to reply with a "yes". I've known Dirk for a few years, starting when we worked on a project that involved C# Code Contracts. Quite some time ago I worked with the Research in Software Engineering group at Microsoft Research, who originally developed Code Contracts, so when I saw Dirk's explanation of the technology, I knew immediately that Dirk has a rare ability to understand, use, and most importantly with regards to C# 7 and .NET Core Cookbook, explain ideas in a clear and precise way.

Most of my colleagues and I believe that a major challenge facing .NET developers, and in fact all software developers, is the astonishing explosion of new technologies and the associated tidal wave of various forms of documentation. It's becoming increasingly difficult to find those few valuable resources that get to the point quickly, and explain technologies and paradigms succinctly so you can get on with your work. This book is one such reference. I hope you'll enjoy and value C# 7 and .NET Core Cookbook as much as I do!

Dr. James McCaffrey

Microsoft Research

About the Author

Dirk Strauss is a software developer and Microsoft .NET MVP from South Africa with over 13 years of programming experience. He has extensive experience in SYSPRO Customization (an ERP system), with C# and web development being his main focus.

He works for Evolution Software, but in all fairness, he can't really call it working at all. When you're having fun and loving what you do with incredibly inspirational individuals, you will not work a day in your life.

He authored the C# Programming Cookbook in 2016 (also published by Packt) and has written for Syncfusion, contributing to the Succinctly series of eBooks.

He also blogs at https://dirkstrauss.com/, whenever he gets a chance.

I would like to thank the team at Evolution Software for being such an incredible source of inspiration to me in my professional and personal life. Working with you folks challenges me to become better at what I do and the way I live my life. Being a part of the Evolution Software team is the most fulfilling experience of my career. It is something that I will always be incredibly grateful for. Last but by no means least, I would like to thank my wife and kids. Thank you for reminding me what life is actually about. Without your love and support, this book would not have been possible. I love you.

About the Reviewer

Fabio Claudio Ferracchiati is a senior consultant and a senior analyst/developer using Microsoft technologies. He works for Agic Technology (http://www.agictech.com). He is a Microsoft Certified Solution Developer for .NET, Microsoft Certified Application Developer for .NET, and Microsoft Certified Professional. He is also a prolific author and a technical reviewer. Over the last ten years, he's written articles for Italian and international magazines, and coauthored more than 10 books on a variety of computer topics.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

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://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787286274.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Sections

Getting ready

How to do it…

How it works…

There's more…

See also

Conventions

Reader feedback

Customer support

Downloading the example code

Errata

Piracy

Questions

New Features in C# 7.0

Introduction

Working with Tuples - getting started

Getting ready

How to do it...

How it works...

Working with Tuples - going deeper

Getting ready

How to do it...

How it works...

Pattern matching

Getting ready

How to do it...

How it works...

Out variables

Getting ready

How to do it...

How it works...

Deconstruction

Getting ready

How to do it...

How it works...

Local functions

Getting ready

How to do it...

How it works...

Improvements to literals

Getting ready

How to do it...

How it works...

Ref returns and locals

Getting ready

How to do it...

How it works...

Generalized async return types

Getting ready

How to do it...

How it works...

Expression bodies for accessors, constructors, and finalizers

Getting ready

How to do it...

How it works...

throw expressions

Getting ready

How to do it...

How it works...

Classes and Generics

Introduction

Creating and implementing an abstract class

Getting ready

How to do it...

How it works...

Creating and implementing an interface

Getting ready

How to do it...

How it works...

Creating and using a generic class or method

Getting ready

How to do it...

How it works...

Creating and using a generic interface

Getting ready

How to do it...

How it works...

Object-Oriented Programming in C#

Introduction

Using inheritance in C#

Getting ready

How to do it...

How it works...

Using abstraction

Getting ready

How to do it...

How it works...

Leveraging encapsulation

Getting ready

How to do it...

How it works...

Implementing polymorphism

Getting ready

How to do it...

How it works...

Single responsibility principle

Getting ready

How to do it...

How it works...

Open/closed principle

Getting ready

How to do it...

How it works...

Exception handling

Getting ready

How to do it...

How it works...

Code Analyzers in Visual Studio

Introduction

Finding and installing analyzers

Getting ready

How to do it...

How it works...

Creating a code analyzer

Getting ready

How to do it...

How it works...

Creating a custom code analyzer

Getting ready

How to do it...

How it works...

Deploying your code analyzer within your organization only

Getting ready

How to do it...

How it works...

Regular Expressions

Introduction

Getting started with regex - Matching a valid date

Getting ready

How to do it...

How it works...

Sanitizing input

Getting ready

How to do it...

How it works...

Dynamic regex matching

Getting ready

How to do it...

How it works...

Working with Files, Streams, and Serialization

Introduction

Creating and extracting ZIP archives

Getting ready

How to do it...

How it works...

In-memory stream compression and decompression

Getting ready

How to do it...

How it works...

Async and await file processing

Getting ready

How to do it...

How it works...

How to make a custom type serializable?

Getting ready

How to do it...

How it works...

Using ISerializable for custom serialization to a FileStream

Getting ready

How to do it...

How it works...

Using XmlSerializer

Getting ready

How to do it...

How it works...

JSON serializers

Getting ready

How to do it...

How it works...

Making Apps Responsive with Asynchronous Programming

Introduction

Return types of asynchronous functions

Getting ready

How to do it...

How it works...

Handling tasks in asynchronous programming

Getting ready

How to do it...

How it works...

Exception handling in asynchronous programming

Getting ready

How to do it...

How it works...

High Performance Programming Using Parallel and Multithreading in C#

Introduction

Creating and aborting a low-priority background thread

Getting ready

How to do it...

How it works...

Increasing the maximum thread pool size

Getting ready

How to do it...

How it works...

Creating multiple threads

Getting ready

How to do it...

How it works...

Locking one thread until the contended resources are available

Getting ready

How to do it...

How it works...

Invoking parallel calls to methods using Parallel.Invoke

Getting ready

How to do it...

How it works...

Using a parallel foreach loop

Getting ready

How to do it...

How it works...

Cancelling a parallel foreach loop

Getting ready

How to do it...

How it works...

Catching errors in parallel foreach loops

Getting ready

How to do it...

How it works...

Debugging multiple threads

Getting ready

How to do it...

How it works...

Composing Event-Based Programs Using Reactive Extensions

Introduction

Installing Rx

Getting ready

How to do it...

How it works...

Events versus observables

Getting ready

How to do it...

How it works...

Using LINQ to perform queries

Getting ready

How to do it...

How it works...

Using schedulers in Rx

Getting ready

How to do it...

How it works...

Debugging lambda expressions

Getting ready

How to do it...

How it works...

Exploring .NET Core 1.1

Introduction

Creating a simple .NET Core application and running it on a Mac

Getting ready

How to do it...

How it works...

Creating your first ASP.NET Core application

Getting ready

How to do it...

How it works

Publishing your ASP.NET Core application

Getting ready

How to do it...

How it works...

ASP.NET Core on the MVC Framework

Introduction

Including middleware and why it is useful

Getting ready

How to do it...

How it works...

Creating Controllers and using routing

Getting ready

How to do it...

How it works...

Rendering Views

Getting ready

How to do it...

How it works...

Choosing and Using a Source Control Strategy

Introduction

Setting up Visual Studio account management and determining which source control solution is best for you

Getting ready

How to do it...

How it works...

Setting up Visual Studio GitHub integration, checking in code for the first time, and checking in changes

Getting ready

How to do it...

How it works...

Working as a team using GitHub, handling and resolving conflicts in code

Getting ready

How to do it...

How it works...

Creating a Mobile Application in Visual Studio

Introduction

Installing Xamarin and other required components on your Windows PC and Mac

Getting ready

How to do it...

How it works...

Creating a mobile application using Apache Cordova

Getting ready

How to do it...

How it works...

Creating an iOS application using Xamarin.Forms and Visual Studio for Mac

Getting ready

How to do it...

How it works...

Writing Secure Code and Debugging in Visual Studio

Introduction

Encrypting and storing passwords correctly

Getting ready

How to do it...

How it works...

Using SecureString in code

Getting ready

How to do it...

How it works...

Securing sensitive parts of the App.config/web.config

Getting ready

How to do it...

How it works...

Preventing SQL injection attacks

Getting ready

How to do it...

How it works...

Using IntelliTrace, diagnostic tools, and historical debugging

Getting ready

How to do it...

How it works...

Setting conditional breakpoints

Getting ready

How to do it...

How it works...

Using PerfTips to identify bottlenecks in code

Getting ready

How to do it...

How it works...

Creating Microservices on Azure Service Fabric

Introduction

Downloading and installing Service Fabric

Getting ready

How to do it...

How it works...

Creating a Service Fabric application with a stateless actor service

Getting ready

How to do it...

How it works...

Using Service Fabric Explorer

Getting ready

How to do it...

How it works...

Azure and Serverless Computing

Introduction

Creating an Azure function

Getting ready

How to do it...

How it works...

Providing print functionality with DocRaptor

Getting ready

How to do it...

How it works...

Using AWS and S3

Getting ready

How to do it...

How it works...

Creating C# Lambda functions with AWS

Getting ready

How to do it...

How it works...

Preface

Visual Studio 2017 allows developers to harness the latest technology and create world-class applications across a variety of platforms. The new language features in C# 7.0 are powerful tools that will allow you to write better functioning software and deliver complex business requirements quicker.

The book takes a look at all of the awesome new features in C# 7. It also looks at how developers can write diagnostic analyzers to produce better code and adhere to specific code standards. It explores .NET Core 1.1 and looks at creating an ASP.NET Core application using the MVC framework.

If creating mobile apps is something you are interested in, this book will show you how to do so using Cordova. If you want to create native iOS applications, this book shows you how to do just that using Visual Studio for Mac.

If serverless computing is something that want to understand more, then look no further. In the book, we take a look at what the term serverless computing means. We also look at how to create an Azure function and how to use AWS and S3. Lastly, hot off the press from Amazon, we take a look at using C# lambda functions with AWS.

This book will show you the beauty of C#, which when combined with the power of Visual Studio, makes you a very formidable developer, capable of meeting a variety of programming challenges head on.

Whatever your skill level when it comes to programming with C#, this book provides something for everyone and will make you a better developer.

What this book covers

Chapter 1, New Features in C# 7.0, shows how C# 7.0 brings a lot of new functionality to the C# language. The biggest of these features by far are Tuples and pattern matching. Getting to grips with what’s new in C# 7.0 is essential for developers in order to stay on top of their game.

Chapter 2, Classes and Generics, form the building blocks of software development and are essential in building good code. The power of classes, which is to describe the world around us and translate it into a programming language that a compiler can understand, allows developers to create great software.

Chapter 3, Object-Oriented Programming in C#, is the foundation of C# and object-oriented programming (OOP). Understanding this concept is essential to .NET developers everywhere.

Chapter 4, Code Analyzers in Visual Studio, talks about how code analyzers help developers to write better code. Be sure that the code you or your team ships measures up to your specific set of code quality standards.

Chapter 5, Regular Expressions, is about how regex make use of patterns that describe a string through the use of special characters that denote a specific bit of text to match. The use of regex, when applied properly, can be a very powerful approach to certain programming problems.

Chapter 6, Working with Files, Streams, and Serialization, teaches the readers that working with files, streams, and serialization is something you as a developer will do many times. Being able to do so correctly will definitely give you an edge as a developer.

Chapter 7, Making Apps Responsive with Asynchronous Programming, talks about how asynchronous programming is an exciting feature in C#. It allows you to continue program execution on the main thread while a long-running task finishes its execution. This enables your applications to remain responsive.

Chapter 8, High Performance Programming Using Parallel and Multithreading in C#, improves your code's performance. Using multithreading and parallel programming can mean the difference between users experiencing an application as working or broken.

Chapter 9, Composing Event-Based Programs Using Reactive Extensions, teaches the reader how Rx is an exciting technology. If you need to create search-as-you-type functionality in an application, have data that changes notify your application instead of having to poll the data all the time (think stock prices), or generally make your app more responsive, the chances are you need to consider using Rx.Chapter 10, Exploring .NET Core 1.1, is about the buzz regarding .NET Core these days. It allows you to create cross-platform applications that run on Windows, Linux, and macOS. Knowing how to use it is essential for all .NET developers.

Chapter 11, ASP.NET Core on the MVC Framework, talks about the MVC framework, which is named according to the MVC design pattern it follows. It allows developers to separate the logic by letting each component of the framework focus on one specific thing. It is this separation of concerns that makes MVC so powerful, especially when combined with .NET Core.Chapter 12, Choosing and Using a Source Control Strategy, is about how source control is an essential part of every developer's toolkit. It doesn't matter whether you are a hobbyist or professional programmer; when you get up from your desk to go home, you'd better be sure your code is safe.

Chapter 13, Creating a Mobile Application in Visual Studio, allows developers to create mobile applications with ease. It also gives developers more choice about how to go about doing it. From creating a mobile app with Xamarin, to using Cordova, to writing native iOS applications with Visual Studio for Mac, .NET developers can expand their service offering using the IDE they know and love.

Chapter 14, Writing Secure Code and Debugging in Visual Studio, talks about how debugging is something developers do more often than not. Being able to do so efficiently is a different story. In a similar way, being able to write secure code is essential to any developer. Creating secure code and being able to efficiently debug that code properly results in a better end product.

Chapter 15, Creating Microservices on Azure Service Fabric, is about how, traditionally, developers wrote applications in a monolithic manner, which is one single executable broken up into components via classes and so on. Microservices is a technology that aims to address the issues surrounding traditional monolithic applications. It allows developers to create smaller bits (services) that can function on their own without being dependent on any of the other services.

Chapter 16, Azure and Serverless Computing, is about how serverless does not mean the lack of a server, but rather you (or the application) does not know which server is used to provide some functionality to an application. Splitting some of your application logic into a serverless-type architecture allows for extreme scalability when loads increase (or decrease), increased performance, and less code to write and debug.

What you need for this book

You will need the latest version of Visual Studio 2017. For some of the chapters on mobile development, you will need an active Apple iTunes account. Regarding the last chapter, you will need to create a free AWS account. Lastly, some of the recipes might also require access to the Azure portal.

Who this book is for

The book will appeal to C# and .NET developers who have a basic familiarity with C# and the Visual Studio 2015 environment.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "You will find the script in the_database scriptsfolder in the accompanying source code."

A block of code is set as follows:

public override void Initialize(AnalysisContext context){ context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType);}

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "From theToolsmenu, selectNuGet Package Managerand thenManage NuGet Packages for Solution...."

Warnings or important notes appear in a box like this.
Tips and tricks appear like this.

Reader feedback

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 .

Customer support

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.

Downloading the example code

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:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/CSharp-7-and-DotNET-Core-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

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

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.

Questions

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.

New Features in C# 7.0

In this first chapter, we will take a look at the C# 7.0 features by covering them in the following recipes:

Working with Tuples - getting started

Working with Tuples - going deeper

Pattern matching

Out variables

Deconstruction

Local functions

Improvements to literals

Ref returns and locals

Generalized async return types

Expression bodies for accessors, constructors, and finalizers

throw expressions

Introduction

C# 7.0 brings a lot of new functionality to the C# language. If you were left wanting more after the release of C# 6.0, then C# 7.0 will not disappoint you at all. It focuses on consuming data, simplifying code, and improving performance. Mads Torgersen who is the C# Program Manager noted that C# 7.0's biggest feature by far is Tuples. The other is pattern matching. These two features (as well as the others) were met with enthusiasm from C# developers worldwide. It is, therefore, no guess that developers will immediately start implementing these new features introduced in C# 7.0. It will, therefore, be very beneficial to get to grips with what C# 7.0 has to offer and implement the new language features in your development projects as soon as possible.

Throughout this book, I will be using the release candidate of Visual Studio 2017. Some features and methods of doing things might change between the time of writing and the final release of Visual Studio 2017.

Working with Tuples - getting started

I have come across many instances where I wanted to return more than one value from a method. As Mads Torgersen pointed out, the existing options available to developers are not optimal. C# 7.0 has, therefore, introduced Tuple types and Tuple literals to allow developers an easy way of returning multiple values from methods. Developers can also rest easy when creating Tuples. Tuples are structs, which are value types. This means that they are created locally and are passed by copying the contents. Tuples are also mutable and Tuple elements are public mutable fields. I am personally very excited about using Tuples. Let's explore Tuples in closer detail in the following recipe.

Getting ready

Start off by creating a regular console application in Visual Studio 2017. Simply call the project you create cookbook. Before I can jump into using Tuples in C# 7.0, I need to add in a NuGet package. Bear in mind that I am using the release candidate of Visual Studio. This process might change between now and the final release of the product.

To do this, head on over to

Tools

,

NuGet Package Manager

and then, click on

Manage NuGet Packages for Solution...

.

Select the

Browse

tab and type in

ValueTuple

in the search box. The

System.ValueTuple by Microsoft

NuGet package should be displayed. Select the

cookbook

project under

Manage Packages for Solution

and click on the

Install

button.

Take note that I am using Visual Studio 2017 RC while writing portions of this book. You probably will not need to addSystem.ValueTuple from NuGet some time in the future after the final release. Adding System.ValueTuple from NuGet might, however, remain a requirement. Only time will tell.

Visual Studio will now show you a prompt to review the changes you are about to make to your project. Just click on the

OK

button. Lastly, you will need to provide the

License Agreement

required by Microsoft. Just click on the

I Accept

button. Visual Studio will now start the NuGet package installation. It will show you its progress in the

Output

window.

After all this is complete, my Visual Studio solution looks as follows:

You will now be ready to create your first method that works with Tuples. Let's see how to do that next.

How it works...

So far in this recipe, we have seen that Tuples give developers a lot of flexibility when you need to return several values from a method. While the dummy implementation of GetAverageAndCount() simply returns the zero-valued Tuple literal, it gives you some idea how Tuples are wired up. This recipe is the foundation for the next recipe. I encourage you to go through both recipes thoroughly in order to gain the full benefit from understanding Tuples and how to use them.

Working with Tuples - going deeper

I will now start adding more meat to the dummy implementation of the GetAverageAndCount() method we created in the previous recipe. If you are new to Tuples, and have not worked through the previous recipe, I encourage you to do so first before starting to work through this recipe.

Getting ready

You need to have completed the code steps in the recipe Working with Tuples - getting started, in order to work through this recipe. Ensure that you have added the required NuGet package as specified in the previous recipe.

Pattern matching

C# 7.0 introduces an aspect common to functional programming languages with pattern matching. This new kind of construct can test values in different ways. To accomplish this, two language constructs in C# 7.0 have been enhanced to take advantage of patterns. These are as follows:

The

is

expression

The

case

clause in

switch

statements

With regard to the is expression, developers can now have a pattern on the right instead of just a type. When it comes to switch statements, the case clause can now match on patterns. The switch statement is no longer limited to primitive types and can switch on anything. Let's start by looking at the is expression.

Getting ready

To illustrate the concept of pattern matching, assume the following scenario. We have two object types called Student and Professor. We want to minimize code, so we want to create a single method to output the data from the object passed to it. This object can be a Student or a Professor