Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
C# 7 and .NET Core Cookbook

You're reading from   C# 7 and .NET Core Cookbook Serverless programming, Microservices and more

Arrow left icon
Product type Paperback
Published in Apr 2017
Publisher
ISBN-13 9781787286276
Length 628 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Dirk Strauss Dirk Strauss
Author Profile Icon Dirk Strauss
Dirk Strauss
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. New Features in C# 7.0 2. Classes and Generics FREE CHAPTER 3. Object-Oriented Programming in C# 4. Code Analyzers in Visual Studio 5. Regular Expressions 6. Working with Files, Streams, and Serialization 7. Making Apps Responsive with Asynchronous Programming 8. High Performance Programming Using Parallel and Multithreading in C# 9. Composing Event-Based Programs Using Reactive Extensions 10. Exploring .NET Core 1.1 11. ASP.NET Core on the MVC Framework 12. Choosing and Using a Source Control Strategy 13. Creating a Mobile Application in Visual Studio 14. Writing Secure Code and Debugging in Visual Studio 15. Creating Microservices on Azure Service Fabric 16. Azure and Serverless Computing

Out variables

C# 7.0 has taken a fresh look at out variables. This is a small change, but really one that improves the readability and flow of the code. Previously, we first had to declare a variable to use as an out parameter in a method. In C# 7.0 we no longer need to do that.

Getting ready

We will be using an often used method to test if a value is of a specific type. Yes, you guessed it, we're going to be using TryParse. I can already hear some of you groan (or is it just me?). Using TryParse is (for me anyway) such a bittersweet thing to do. It's great being able to try and parse something to test if it is valid, but the use of the out variable was never as neat and tidy as I would have liked. If you are not familiar with the TryParse method, it is a method that tests to see if a value parses to a specific type. If it does, TryParse will return a Boolean value of true ; otherwise, it will return false.

How to do it...

  1. The following code example will illustrate how we used to have to use TryParse to check if a string value is a valid integer. You will notice that we had to declare the integer variable intVal, which was used as the out variable. The intVal variable would just sort of hang there in mid air, usually not initialized and waiting to be used in TryParse.
        string sValue = "500";

int intVal;
if (int.TryParse(sValue, out intVal))
{
WriteLine($"{intVal} is a valid integer");
// Do something with intVal
}
  1. In C# 7.0 this has been simplified, as can be seen in the following code example. We can now declare the out variable at the point where it is passed as an out parameter, like so:
        if (int.TryParse(sValue, out int intVal))
{
WriteLine($"{intVal} is a valid integer");
// Do something with intVal
}
  1. This is a small change, but a very nice one. Run the console application and check the output displayed.
  1. As we are declaring the out variable as an argument to the out parameter, the compiler will be able to infer what the type should be. This means that we can also use the var keyword, like this:
        if (int.TryParse(sValue, out var intVal))
{
WriteLine($"{intVal} is a valid integer");
// Do something with intVal
}

How it works...

The changes that C# 7.0 has made to out variables are not major. They are, however, a major convenience to those developers who use it often. So far in this chapter, we have seen the use of Tuples, pattern matching, and out variables. We can easily combine some of what we have learned to create something truly unique. Consider the use of extension methods, Tuples, and out variables. We can easily create an extension method called ToInt() that has the following implementation:

public static (string originalValue, int integerValue, bool isInteger) ToInt(this string stringValue)
{
var t = (original: stringValue, toIntegerValue: 0, isInt: false);
if (int.TryParse(stringValue, out var iValue))
{
t.toIntegerValue = iValue; t.isInt = true;
}
return t;
}

We create a Tuple literal that will be returned in the event of the TryParse returning false. If the TryParse is true, I set the t.toIntegerValue and t.isInt values. The code that calls the extension method looks as follows:

var (original, intVal, isInteger) = sValue.ToInt();
if (isInteger)
{
WriteLine($"{original} is a valid integer");
// Do something with intVal
}

When you run your console application, you will see that the output is exactly the same as before. This just illustrates the power of the new features in C# 7.0 when combined with each other. Throw some pattern matching into the mix, and we will have a very potent extension method. I'll leave you folks to play around with this some more. There is a lot to discover.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image