C# 7.0 And C# 7.1 New Features

This article explains the new features of C# 7.0 & C#7.1. It covers all the latest features such as Discards, Pattern Matching, Generalized async return types, Async Main (Main Method returning Task), Infer Tuple Element Names, Default Literal Expressions & Type Inference and Pattern Matching with Generics.

This article is the second article of the series New Features of C# 7.x.  If you missed the first part of this article, then I recommend you to go through the below-provided link.

Top 10 New Features of C# 7 With Visual Studio 2017

In the preceding article, I covered following features of C# 7.0.

  1. Local Functions or Nested Functions
  2. Binary Literals
  3. Digit Separators
  4. Pattern matching
  5. ref returns and ref Locals
  6. Tuples (Tuples Enhancement)
  7. Throw Expressions
  8. Expression Bodied Members (methods, properties, constructors, destructors, getters, setters, indexers, operators, Main method)
  9. Out variables (enhancement for out variables)
  10. Deconstruction

Rather than using term C# 7.0, C# 7.1 and C# 7.2, C# 7.3, I may be using the term C# 7.x instead.

Topics covered in this article

I am going to cover following features of C# 7.x in this article.

  1. Discards (C# 7.0)

    1. Out parameter variable in C# 7 with Discard
    2. Discard multiple parameter names
    3. Discard multiple variable names and their data types
    4. Discard with tuples
    5. Using Discard standalone
    6. Using Discard with the ‘is’ expression Pattern Matching
    7. Discard with Tasks
    8. Simplest and smallest example of Discard
  1. Pattern Matching (C# 7.0)

    1. The ‘is’ type Pattern Matching
    2. “switch” Statement Pattern Matching
    3. “switch” Statement with “when” condition Pattern Matching
    4. Does Sequence Matters for Switch Case Expression in C# 7.x? (Big change)

  2. Generalized async return types (C# 7.0)

    1. Async method returning Task
    2. Async method returning Task<T>
    3. Async method returning void
    4. Async method returning ValueTask <T>
  1. Async Main: Main Method returning Task (C# 7.1)

    1. Understanding the Existing Functionality and Behaviour of Main Method
    2. What is new in C# 7.1 for Main Method

  2. Infer Tuple Element Names (C# 7.1)

    1. Using Tuple before C# 7.0
    2. Using Tuple in C# 7: Without Using the Tuple Keyword
    3. Using Tuple in C# 7: Accessing member with meaningful name
    4. Using Tuple in C# 7: Deconstructing Tuple
    5. Using Tuple in C# 7.1: Inferring element name

  3. Default Literal Expressions and Type Inference (C# 7.1)

    1. Overview of Default Literal Expressions before C# 7.1
    2. Enhancement for Default Literal Expressions in C# 7.1

  4. Pattern Matching with Generics (C# 7.1)
1. Discards

C# 7 allows us to discard the returned value which is not required. Underscore (_) character is used for discarding the parameter. The discard parameter (_) is also referred to as write-only. We cannot read the value from this parameter.

Out parameter Discard in C# 7

C#

Before jumping to discard, I want to explain about out keyword in C#. Have a look at the below code snippet.

Before C# 7

  1. WriteLine("Please enter a numeric value");  
  2. int x;  
  3. if (int.TryParse(ReadLine(), out x))  
  4. {  
  5.     WriteLine("Entered data is a number");  
  6. }    

You can see that in the preceding code snippet, I am just trying to convert a string to an integer. If it is converted successfully, then I am printing a message.

Out variable in C# 7 without Discard

In C# 7, we can declare out variable as inline variable so the preceding code snippet can be written as -

  1. WriteLine("Please enter a numeric value");  
  2. if (int.TryParse(ReadLine(), out int x))  
  3. {  
  4.     WriteLine("Entered data is a number");  
  5. }  
Out variable in C# 7 with Discard

As you see, I am using a local variable x just for passing it as a parameter but I am using this variable nowhere. So, if the variable is not used, then it should not have a name and no value should be assigned to it.

Discard does the same thing, i.e. instead of using the variable name, we can just use the underscore character.

  1. WriteLine("Please enter a numeric value");  
  2. if (int.TryParse(ReadLine(), out int _))  
  3. {  
  4.     WriteLine("Entered data is number");    
  5. }  

This discard option is not limited to a single variable. You can use discard with any number of variable. Let’s try to understand it with another example.

Write a function with name Result which accepts 2 integers and returns sum, difference, multiplication, division, and modular division of these 2 numbers.

  1. private static void Result(int x, int y, out int sum, out int diff, out int mult, out int div, out int modDiv)  
  2.         {  
  3.             sum = x + y;  
  4.             diff = x - y;  
  5.             mult = x * y;  
  6.             div = x / y;  
  7.             modDiv = x % y;  
  8.         }  

 And, call it like -

  1. int a=10, b=20, sum, diff, mult, div, modDiv;  
  2. Result(a, b, out sum, out diff, out mult, out div, out modDiv);  
  3. WriteLine($"Sum of {a} and {b} is {sum}");  

In Visual Studio 2017, you notice that it shows 3 dots for each variable which can be declared inline. So, you can call the Result method by using the below code snippet.

  1. int a=10, b=20;  
  2. Result(a, b, out int sum, out int diff, out int mult, out int div, out int modDiv);  
  3. WriteLine($"Sum of {a} and {b} is {sum}");  
Discard multiple out parameter names

However, I am using only the variable “sum” but not using the variable “diff”, “mult”, “div” and “modDiv”, so I can replace all these by the underscore (_) characters as shown in the below code snippet.

  1. int a=10, b=20;  
  2. Result(a, b, out int sum, out int _, out int _, out int _, out int _);  
  3. WriteLine($"Sum of {a} and {b} is {sum}");  

So, you can see how we are discarding the variable we are not using.

Discard multiple out parameters names and their data types

You know that I am not passing the variable name but data type passed. However, datatype passing is also optional, and we can remove data type as well. Following is the code snippet for the same.

  1. int a=10, b=20;  
  2. Result(a, b, out int sum, out _, out _, out _, out _);  
  3. WriteLine($"Sum of {a} and {b} is {sum}");  
Discard with tuples

C#

You can see in the preceding screenshot that I need only product id and product name, so I have discarded all other parameters of the tuple.

Following is the complete code for the same

  1. using static System.Console;  
  2. namespace DiscardExampleWithTuple  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             Program p = new Program();  
  9.               
  10.             //calling tuple without discard  
  11.             //(int id, string name, string desc, double price, double rating, string cat) = p.GetProduct(101);  
  12.   
  13.             //calling tuple with discard  
  14.             (int id, string name, _, _, _, _) = p.GetProduct(101);  
  15.             WriteLine($"id: {id} name: {name}");  
  16.         }  
  17.   
  18.         (int productId, string productName, string productDescription, double productPrice,  
  19.             double customerRating, string productCategory) GetProduct(int productId) => (productId, "Wireless Mouse""Wireless mouse. connect with usb...", 200.00, 4.6, "Computer accesories");  
  20.     }  
  21. }  
Using Discard standalone

Have a look at the below code snippet.

  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.         int x = 20;  
  6.           var recordsUpdated= x > 20 ? UpdateCustomer() : UpdateProduct();  
  7.         }  
  8.   
  9.         private static int UpdateCustomer()  
  10.         {  
  11.             int recordsUpdated = 0;  
  12.             //update customer logic  
  13.             recordsUpdated = 5;  
  14.             return recordsUpdated;  
  15.         }  
  16.   
  17.         private static int UpdateProduct()  
  18.         {  
  19.             int recordsUpdated = 0;  
  20.             //update product logic  
  21.             recordsUpdated = 10;  
  22.             return recordsUpdated;  
  23.         }  
  24.   
  25.     }  

You can see that I am calling UpdateCustomer() & UpdateProduct() method conditionally in ternary operator.

  1. var recordsUpdated= x > 20 ? UpdateCustomer() : UpdateProduct();  

So, I am calling 2 methods conditionally and storing the result in a variable “recordsUpdated”. But, I am not using the value of variable “recordsUpdated”. So, let’s call it like below.

  1. x > 20 ? UpdateCustomer() : UpdateProduct();  

You get the compiler error. Following is the screenshot for the same.

C#

Now, resolve it using discard and call it like the following statement.

  1. _=x > 20 ? UpdateCustomer() : UpdateProduct();  
Discard with Pattern Matching

In case of pattern matching, discard can be used with ‘is’ expression.

Discard with ‘is’ expression
  1. private static void DoSomething(dynamic x)  
  2. {  
  3.     if (x is int) WriteLine(" x is int");  
  4.     if (x is null) WriteLine(" x is null");             
  5.     if (x is string) WriteLine(" x is string");             
  6.     else if (x is var _) WriteLine(" not sure about the type of x");  
  7. }  
Discard with Tasks

Let’s have a look at the below code snippet.

  1. static void Main(string[] args) => PrintOddNumbers(20);  
  2.   
  3. private static void PrintOddNumbers(int maxNumber)  
  4. {  
  5.   Task task = Run(() => {   
  6.     for (int i = 1; i < maxNumber; i += 2)  
  7.     {  
  8.         Write($"{i}\t");  
  9.         Sleep(500);  
  10.     }  
  11.     });              
  12.    Delay(300*maxNumber).Wait();  
  13. }  

You can see that in the above code snippet, I am creating a variable with name “task” but I am not using it. So, it can be discarded and we can write it as -

  1. private static void PrintOddNumbers(int maxNumber)  
  2. {  
  3.   _= Run(() => {   
  4.     for (int i = 1; i < maxNumber; i += 2)  
  5.     {  
  6.         Write($"{i}\t");  
  7.         Sleep(500);  
  8.     }  
  9.     });              
  10.    Delay(300*maxNumber).Wait();  
  11. }  

I am just showing an example to explain how to use discard with the task, but the above code snippet can be optimized.

Simplest and smallest example of Discard

Below code snippet is one of the simplest and smallest examples of discard.

  1. static void Main(string[] args) => _=10+20;  
 
2. Pattern Matching

Pattern matching is one of the most popular features of C# 7. I also explained pattern matching in my previous article, but right I am going to explain it in depth.

The ‘is’ type Pattern Matching

The ‘is’ keyword is not new to C#, but in C# 7, you can assign it to a new variable in the same expression.

Before C# 7

  1. private static void PrintObject(dynamic x)  
  2. {  
  3.     if (x is Customer)  
  4.     {  
  5.         var c = x as Customer;  
  6.         WriteLine($"Customer Id : {c.Id} Customer Name {c.Name}");  
  7.     }  
  8.     if (x is Product)  
  9.     {  
  10.         var p = x as Product;  
  11.         WriteLine($"Product Id : {p.ProductId} Product Name {p.Name}");  
  12.     }  
  13.     else  
  14.         WriteLine("Unknown type");  
  15. }  

In C# 7

  1. private static void PrintObject(dynamic x)  
  2.         {  
  3.             if (x is Customer c)  
  4.                 WriteLine($"Customer Id : {c.Id} Customer Name {c.Name}");  
  5.             if (x is Product p)  
  6.                 WriteLine($"Product Id : {p.ProductId} Product Name {p.Name}");  
  7.             else  
  8.                 WriteLine("Unknown type");  
  9.         }  

If you compile the above statement in C# 6 or below version, then you get compile time error.

C#

So, you can see that in C# 7, as soon as the type matches, we can assign it to a new variable.

“switch” Statement Pattern Matching

Before C# 7, we could not use pattern matching with switch expression. In C# 6 and earlier versions, limited types were supported and that must had been a compile time constant otherwise you get the following error.

“A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type in C# 6 and earlier.”

Let’s use the same example which I have used for ‘is’ pattern matching and convert the code to switch expression.

In C# 7

  1. private static void PrintObject(dynamic x)  
  2.         {  
  3.             switch (x)  
  4.             {  
  5.                 case Customer c:  
  6.                     WriteLine($"Customer Id : {c.Id} Customer Name {c.Name}");  
  7.                     break;  
  8.                 case Product p:  
  9.                     WriteLine($"Product Id : {p.ProductId} Product Name {p.Name}");  
  10.                     break;  
  11.                 default:  
  12.                     WriteLine("Unknown type");  
  13.                     break;  
  14.             }              
  15.         }  

Compile “switch” Statement Pattern Matching with C# 6

Now, try to compile the same in C# 6. You get the errors as shown in the following screenshot.

C#

“switch” Statement “when” condition Pattern Matching

In C# 7, we can use “when” with switch case for better pattern matching.

  1. private void PrintShapeType(object shape)  
  2.         {  
  3.             switch (shape)  
  4.             {  
  5.                 case Triangle t when t.SideA == t.SideB && t.SideB == t.SideC:  
  6.                     WriteLine($"Equilateral Triangle");  
  7.                     break;  
  8.   
  9.                 case Triangle t:  
  10.                     WriteLine($"Not a Equilateral Triangle");  
  11.                     break;  
  12.   
  13.                 case Rectangle r when r.Height == r.Width:  
  14.                     WriteLine($"Square");  
  15.                     break;  
  16.   
  17.                 case Rectangle r:  
  18.                     WriteLine($"Rectangle");  
  19.                     break;  
  20.   
  21.                 default:  
  22.                     WriteLine($"Unknow shape");  
  23.                     break;  
  24.             }  
  25.         }  
Does Sequence Matters for Switch Case Expression in C# 7.x? (Big change)

If we talk about the sequence for case expression, apparently, the answer is YES. In C# 7.0 and above versions, sequence matters for case expression.

Let’s create a simple console app to prove that statement. Create a console app with following code snippet.

  1. using static System.Console;  
  2. namespace CaseExpressionSequence  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             PrintData(0);  
  9.             PrintData(2);  
  10.             PrintData(5);  
  11.             PrintData(false);  
  12.             PrintData(true);  
  13.             PrintData(55.5);  
  14.         }  
  15.   
  16.         private static void PrintData(object obj)  
  17.         {  
  18.             switch (obj)  
  19.             {  
  20.                 case 0:  
  21.                 case 5:  
  22.                 case true:  
  23.                     WriteLine($"you passed {obj}");  
  24.                     break;  
  25.                 case int number:  
  26.                     WriteLine($"you passed a numeric value");  
  27.                     break;  
  28.                 case bool b:  
  29.                     WriteLine($"you passed a boolean value");  
  30.                     break;  
  31.                 default:  
  32.                     WriteLine($"Invalid data");  
  33.                     break;  
  34.             }  
  35.         }  
  36.     }  
  37. }  

Output

C#

You can see that in the above code snippet, when I am passing 0, 5, & true, then it has more than one matching conditions but the code is being executed for the first matching block. This is a significant change and you must remember it.

3. Generalized async return types

Before going through the generalized async, let’s have a look on asynchronous programming and try to understand it how it works.

Async method returning Task
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             PrintPrimeNumbers(100);  
  6.             ReadKey();  
  7.         }  
  8.   
  9.         private static async Task PrintPrimeNumbers(int maxNumber)  
  10.         {  
  11.             await Run(() =>  
  12.                {  
  13.                    WriteLine($"printing prime numbers between 0 and {maxNumber}");  
  14.                    List<int> primes = new List<int>();  
  15.                    bool isPrime;  
  16.   
  17.                    for (int number = 2; number <= maxNumber; number++)  
  18.                    {  
  19.                        isPrime = true;  
  20.                        foreach (var prime in primes.Where(x => x <= Sqrt(number)))  
  21.                        {  
  22.                            if (number % prime == 0)  
  23.                            {  
  24.                                isPrime = false;  
  25.                                break;  
  26.                            }  
  27.                        }  
  28.                        if (isPrime)  
  29.                        {  
  30.                            WriteLine(number);  
  31.                            primes.Add(number);  
  32.                        }  
  33.                    }  
  34.                });  
  35.         }  
  36.     }  
Async method returning Task<T>

You can see that the return type of the method “PrintPrimeNumbers()” is Task.

Now, change the return type of the method as Task<T>.

  1. static void Main(string[] args)  
  2. {  
  3.     int x = GetLargestPrimeNumber(100).Result;  
  4.     WriteLine(x);  
  5.     ReadKey();  
  6. }  
  7.   
  8. private static async Task<int> GetLargestPrimeNumber(int maxNumber)  
  9. {  
  10.     List<int> primes = new List<int>();  
  11.     await Run(() =>  
  12.     {  
  13.         bool isPrime;  
  14.         for (int number = 2; number <= maxNumber; number++)  
  15.         {  
  16.             isPrime = true;  
  17.             foreach (var prime in primes.Where(x => x <= Sqrt(number)))  
  18.             {  
  19.                 if (number % prime == 0)  
  20.                 {  
  21.                     isPrime = false;  
  22.                     break;  
  23.                 }  
  24.             }  
  25.             if (isPrime)  
  26.             {  
  27.                 primes.Add(number);  
  28.             }  
  29.         }  
  30.     });  
  31.     return primes.Max();  
  32. }  
Async method returning void
  1. static void Main(string[] args)  
  2. {  
  3.     PrintPrimeNumber(20);  
  4.     ReadKey();  
  5. }  
  6. private static async void PrintPrimeNumber(int maxNumber)  
  7.         {  
  8.             await Run(() =>  
  9.             {  
  10.                 WriteLine($"printing prime numbers between 0 and {maxNumber}");  
  11.                 List<int> primes = new List<int>();  
  12.                 bool isPrime;  
  13.   
  14.                 for (int number = 2; number <= maxNumber; number++)  
  15.                 {  
  16.                     isPrime = true;  
  17.                     foreach (var prime in primes.Where(x => x <= Sqrt(number)))  
  18.                     {  
  19.                         if (number % prime == 0)  
  20.                         {  
  21.                             isPrime = false;  
  22.                             break;  
  23.                         }  
  24.                     }  
  25.                     if (isPrime)  
  26.                     {  
  27.                         WriteLine(number);  
  28.                         primes.Add(number);  
  29.                     }  
  30.                 }  
  31.             });  
  32.         }  

Async method returning ValueTask <T>

So far, you have seen that an async method can return Task, Task<T>, and void. However, rather than returning Task<T>, it would be better if we can return anything because Task is a class, i.e. reference type which may not be right in multiple scenarios because reference type behaves differently in C#.

In C# 7, there is an inbuilt value type ValueTask <T> which can be used instead of Task<T>. Below is the code snippet for the same.

  1. static void Main(string[] args)  
  2.         {  
  3.            int x= GetLargestPrimeNumber(20).Result;  
  4.             ReadKey();  
  5.         }  
  6. private static async ValueTask<int> GetLargestPrimeNumber(int maxNumber)  
  7.         {  
  8.             List<int> primes = new List<int>();  
  9.             await Run(() =>  
  10.             {  
  11.                 bool isPrime;  
  12.                 for (int number = 2; number <= maxNumber; number++)  
  13.                 {  
  14.                     isPrime = true;  
  15.                     foreach (var prime in primes.Where(x => x <= Sqrt(number)))  
  16.                     {  
  17.                         if (number % prime == 0)  
  18.                         {  
  19.                             isPrime = false;  
  20.                             break;  
  21.                         }  
  22.                     }  
  23.                     if (isPrime)  
  24.                     {  
  25.                         primes.Add(number);  
  26.                     }  
  27.                 }  
  28.             });  
  29.             return primes.Max();  
  30.         }  

To use ValueTask<T>, you must need to install NuGet package “System.Threading.Tasks.Extensions”.

If you do not remember the package name, then you do not need to worry about it. As soon as you write the ValueTuple<T>, you get a suggestion for installing it, as shown in the following screenshot.

C#

 

C#

If NuGet package “System.Threading.Tasks.Extensions” is already installed for any other project, it shows you that you can use the local version.

You may be thinking that I was talking about the term generalized async, but here you are getting only ValueTuple<T>. So, I would like to clarify that you can create your type which can be the return type of async method. However, if you do not want to create your type, then you can use ValueTuple<T> which is already available.

If you would like to create your custom type, then please visit here.

4. Async Main (Main Method returning Task)

In C# 7.1, support for the “async Main” method has been added. I have already discussed a lot about async methods and you can understand the behavior of async.

C#

Understanding the Existing Functionality and Behaviour of Main Method

However, before jumping to the syntax of Async Main method let’s try to understand the current behaviour of the Main method.

Question 1 Can we have more than one Main method in a Project?

Answer

Yes, we can have more than one Main method in a Project. However, in that case, we need to specify the entry point otherwise it gives compile time error.

Just try to compile the below code snippet

  1. using static System.Console;  
  2. namespace MultipleMain  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args) => WriteLine($"class B");  
  7.     }  
  8.     class A  
  9.     {  
  10.         static void Main(string[] args) => WriteLine($"class A");  
  11.     }  

And you will get the compile-time error. Below is the screenshot for the same.

C#

If you are compiling it from the command prompt, then you have to compile with /main.

In case of Visual studio follow the below steps to specify the entry point.

Right click on your project => Properties => on Application Tab => Startup object,

C#

Question 2: What is the allowed syntax of the Main method which is considered as an entry point.

Before C# 7.1, the Main method can have following signatures which are considered as entry points.

  1. Static Main method with return type void and argument as string array
  2. Static Main method with return type void and without any arguments
  3. Static Main method with return type “int” and argument as string array
  4. Static Main method with return type “int” and without any arguments
  1. static void Main(string[] args)     //Example 1  
  2. static void Main()          //Example 2  
  3. static int Main(string[] args)  //Example 3  
  4. static int Main()           //Example 4  

Complete code

  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         WriteLine("Static Main method with return type void and argument as string array");  
  6.     }  
  7.   
  8.     static void Main()  
  9.     {  
  10.         WriteLine("Static Main method with return type void and without any arguments");  
  11.     }  
  12.   
  13.     static int Main(string[] args)  
  14.     {  
  15.         WriteLine("Static Main method with return type “int” and argument as string array");   
  16.         return 0;  
  17.     }  
  18.   
  19.     static int Main()  
  20.     {  
  21.         WriteLine("Static Main method with return type “int” and without any arguments");  
  22.         return 0;  
  23.     }  
  24. }  

If you are using any other signature for “Main” method apart from the above 4 mentioned signatures, then it is not considered as an entry point.

C#

What is new in C# 7.1 for Main Method

In C# 7.1 support for async “Main” has been added. Thus, in C# 7.1 following signatures for the Main method has been added which are allowed as entry point

  1. static async Task Main()            //Example 1  
  2. static Task Main()              //Example 2  
  3. static async Task<int> Main()             //Example 3  
  4. static Task<int> Main()               //Example 4  
  5. static async Task Main(string[] args)       //Example 5  
  6. static Task Main(string[] args)             //Example 6  
  7. static async Task<int> Main(string[] args)    //Example 7  
  8. static Task<int> Main(string[] args)      //Example 8  
Is Generalized Async supported by the Main method

Generalized async is not supported by the Main method.

C#

You can see in the above screenshot that I am using ValueTask<int> but it gives a compilation error.

How to remember all the signature of the Main method allowed as entry point

You know that if we include the signature of the Main method allowed as entry point till C# 7.1 then it becomes 12 so you think that how you can remember all the signature, then I would like to tell you that it is straightforward. Just remember these rules

Parameters: It can be Parameterless or have parameter as “string[]”

Return Type: void, int, Task & Task<int>

Async: can be used with Task and Task<int>

Apart from the above mentioned 12 signatures the Main method may have dozens of more signatures, but the Main method with that signature is not allowed as an entry point.

5. Infer Tuple Element Names

C# 7.1 has added support for inferring the tuple name.  I have already explained a lot about tuple in the previous article you can read there about tuple enhancement done in C# 7.0. Let’s have a quick look in brief,

Using Tuple before C# 7.0
  1. using System;  
  2. namespace TupleExampleWithCsharp4_0  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             var activity=ActivityTracker.GetActivity();  
  9.             Console.WriteLine("Activity Data: \n Steps: {0}\n Distance: {1} Km.\n Calories Burned: {2}\n Sleep Time: {3}\n Heart Rate: {4}\n Weight: {5}", activity.Item1, activity.Item2, activity.Item3, activity.Item4, activity.Item5, activity.Item6);  
  10.         }  
  11.     }  
  12.   
  13.     public class ActivityTracker  
  14.     {  
  15.         public static Tuple<int,double,double,TimeSpan,double,double> GetActivity()  
  16.         {  
  17.             int steps = 7000;  
  18.             double distance = 5.2;  
  19.             double caloriesBurned = 30.02;  
  20.             TimeSpan sleepTime = new TimeSpan(6, 20, 00);  
  21.             double heartRate = 72;  
  22.             double weight = 75.5;  
  23.             Tuple< int,double,double, TimeSpan,double,double> activity = new Tuple<intdoubledouble, TimeSpan, doubledouble> (steps, distance, caloriesBurned, sleepTime, heartRate, weight);  
  24.             return activity;  
  25.         }  
  26.     }  
  27. }  

C#

Using Tuple in C# 7 - Without Using the Tuple Keyword
  1. using System;  
  2. using static System.Console;  
  3.   
  4. namespace TupleExampleWithCsharp7_0  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             var activity = ActivityTracker.GetActivity();  
  11.             WriteLine($"Activity Data: \n Steps: {activity.Item1}\n Distance: {activity.Item2} Km.\n Calories Burned: {activity.Item2}\n Sleep Time: {activity.Item4}\n Heart Rate: {activity.Item5}\n Weight: {activity.Item6}");  
  12.         }  
  13.     }  
  14.   
  15.     public class ActivityTracker  
  16.     {  
  17.         public static (intdoubledouble, TimeSpan, doubledouble) GetActivity()  
  18.         {  
  19.             int steps = 7000;  
  20.             double distance = 5.2;  
  21.             double caloriesBurned = 30.02;  
  22.             TimeSpan sleepTime = new TimeSpan(6, 20, 00);  
  23.             double heartRate = 72;  
  24.             double weight = 75.5;  
  25.             var activity = (steps, distance, caloriesBurned, sleepTime, heartRate, weight);  
  26.             return activity;  
  27.         }  
  28.     }  
  29. }  
Using Tuple in C# 7 Accessing member with meaningful name
  1. using System;  
  2. using static System.Console;  
  3. using static TupleWithMemberName.ActivityTracker;  
  4.   
  5. namespace TupleWithMemberName  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             var activity = GetActivity();  
  12.             WriteLine($"Activity Data: \n Steps: {activity.steps}\n Distance: {activity.distance} Km.\n Calories Burned: {activity.caloriesBurned}\n Sleep Time: {activity.sleepTime}\n Heart Rate: {activity.heartRate}\n Weight: {activity.weight}");  
  13.         }  
  14.     }  
  15.   
  16.     public class ActivityTracker  
  17.     {  
  18.         public static (int steps, double distance, double caloriesBurned, TimeSpan sleepTime, double heartRate, double weight) GetActivity() => (steps: 7000, distance: 5.2, caloriesBurned: 30.02, sleepTime: new TimeSpan(6, 20, 00), heartRate: 72, weight: 75.5);  
  19.     }  
  20. }  
Using Tuple in C# 7 Deconstructing Tuple
  1. using System;  
  2. using static System.Console;  
  3.   
  4. namespace TupleDeConstruct  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             (int steps, double distance, double caloriesBurned, TimeSpan sleepTime, double heartRate, double weight) = GetActivity();  
  11.             WriteLine($"Activity Data: \n Steps: {steps}\n Distance: {distance} Km.\n Calories Burned: {caloriesBurned}\n Sleep Time: {sleepTime}\n Heart Rate: {heartRate}\n Weight: {weight}");  
  12.         }  
  13.   
  14.         public static (int steps, double distance, double caloriesBurned, TimeSpan sleepTime, double heartRate, double weight) GetActivity() => (steps: 7000, distance: 5.2, caloriesBurned: 30.02, sleepTime: new TimeSpan(6, 20, 00), heartRate: 72, weight: 75.5);  
  15.     }  
  16. }  
Using Tuple in C# 7 Deconstructing Tuple Example 2
  1. static void Main(string[] args)  
  2.         {  
  3.             (int steps, double distance,_,_,_,_) = GetActivity();  
  4.             WriteLine($"Activity Data: \n Steps: {steps}\n Distance: {distance} Km.");  
  5.         }  
  6.   
  7.         public static (intdoubledouble, TimeSpan, doubledouble) GetActivity()   
  8.             => (7000, 5.2,30.02,new TimeSpan(6, 20, 00),72,75.5);  

Using Tuple in C# 7.1 Inferring element name

Now try to compile the following code snippet in C# 7.0.

  1. public static void GetActivity()  
  2.  {  
  3.      int steps = 7000;  
  4.      double distance = 5.2;  
  5.      double caloriesBurned = 30.02;  
  6.      TimeSpan sleepTime = new TimeSpan(6, 20, 00);  
  7.      double heartRate = 72;  
  8.      double weight = 75.5;  
  9.      var activity = (steps, distance, caloriesBurned, sleepTime, heartRate, weight);  
  10.   
  11.      WriteLine($"Activity Data: \n Steps: {activity.steps}\n Distance: {activity.distance} Km.");  
  12.  }  

Please visit the below-provided links for the details of how to change C# language version

You will get a compilation error for the above code snippet. Following is  the screenshot for the same.

C#
However, if you look at the error message you will notice that it is saying that Tuple element name is inferred and suggesting you use C# 7.1.

On mouse hover you will get a similar type of suggestion and “Quick Actions” light bulb will also suggest you do the same thing shown in the following screenshot.

C#

Now change the C# language version to C# 7.1 by just clicking on the “Quick Actions” options and re-compile your code. You will notice that it gets compiled successfully and following is output for the same.

C#

6. Default Literal Expressions and Type InferenceC#
 
Overview of Default Literal Expressions before C# 7.1

‘default’ keyword is not a new keyword in C#. It is being used for  a long time. However, some enhancement has been done for ‘default literal expression’.

There are multiple examples where we need to use the default value of a variable. Below are some examples of the same,

  1. int a = 0;  
  2.         bool b = false;  
  3.         string c = null;  
  4.         int? d = null;  

In the above code snippet, you can see that I am assigning default values for value type and reference type explicitly.

Now replace the datatype keywords with ‘var’ and you see that you are not able to compile your code

C#

If you look at the above code snippet, you will notice that there 2 issues:

  1. You must know default value of all types that you are using.
  2. Null cannot be assigned to an implicitly-typed

The solution is “default”. Using the default keyword, the above code snippet can be written as:

  1. var a = default(int);  
  2. var b = default(bool);  
  3. var c = default(string);  
  4. var d = default(int?); 

That’s fine. Now take another exmple and have a look at the below code snippet.

  1. int a = default(int);  
  2.  bool b = default(bool);  
  3.  string c = default(string);  
  4.  int? d = default(int?);  
  5.  Action<int, bool> action = default(Action<int, bool>);  
  6.  Predicate<string> predicate = default(Predicate<string>);  
  7.  List<string> list = default(List<string>);  
  8.  Dictionary<int, string> dictionary = default(Dictionary<int, string>);  
  9. public int Add(int x, int y= default(int), int z=default(int))  
  10.  {  
  11.      return x + y + z;  
  12.  } 

So, in the above code snippet, you can see that rather than providing their default values explicitly I am using the default keyword to get their default values.

Enhancement done for Default Literal Expressions in C# 7.1

In C# 7.1 enhancement has been done for Default Literal Expressions and Type Inference and we can write the previous statement as follows,

  1. int a = default;  
  2. bool b = default;  
  3. string c = default;  
  4. int? d = default;  
  5. Action<int, bool> action = default;  
  6. Predicate<string> predicate = default;  
  7. List<string> list = default;  
  8. Dictionary<int, string> dictionary = default;  
  9. public int Add(int x, int y = defaultint z = default)  
  10.  {  
  11.      return x + y + z;  
  12.  } 

If you are using the above statement in C# 7.0 then it gives error and suggest you use C# 7.1. Whereas if you are using it in C# 7.1 and providing type details in right-hand side of the statement then it suggests you simplify the code.

C#

7. Pattern Matching with Generics

Pattern matching is one of the most popular features introduced with C# 7.0, and it supports many patters which I have already explained earlier in this article. However, Pattern matching with generic was not supported with C# 7.0. It has been added in C# 7.1. Let’s have a look at the below code snippets, 

Pattern Matching with Generics Example 1
  1. public void PrintProduct<T>(T product) where T:Product  
  2. {  
  3.     switch (product)  
  4.     {  
  5.         case ConvenienceProduct p:  
  6.             WriteLine("Convenience Product");  
  7.             // ---- print other information  
  8.             break;  
  9.         case ShoppingProduct p:  
  10.             WriteLine("Shopping Product");  
  11.             // ---- print other information  
  12.             break;  
  13.   
  14.         case SpecialtyProduct p:  
  15.             WriteLine("Specialty Product");  
  16.             // ---- print other information  
  17.             break;  
  18.         default:  
  19.             WriteLine("General Product");  
  20.             break;  
  21.     }  

Pattern Matching with Generics Example 2 

  1. public void Print<T>(T type) where T : class  
  2. {  
  3.     switch (type)  
  4.     {  
  5.         case Customer customer:  
  6.             WriteLine($"{customer.Id} {customer.Name} {customer.CustomerType} {customer.MonthlyPurchase}");  
  7.             break;  
  8.         case Product product:  
  9.             WriteLine($"{product.ProductId} {product.ProductName} {product.ProductDescription}");  
  10.             break;  
  11.         default:  
  12.             break;  
  13.     }  

You can see in the previous two code snippets that in the switch statement, now I can use generics. However, if you will try to compile the above two code snippets in C# 7.0, these will not get compiled and suggest you to use C# 7.1.

SO far, I have covered a lot from C# 7.0 and C# 7.1. In the next article, i.e. the third article of the series, I will be explaining the new features added in C# 7.2 and above versions. You can go through the below-provided links for my other articles of C# 7.

Author
Banketeshvar Narayan
0 15.8k 5.7m
Next » Tuple In C# 7