Top New Features in C# 7.0

0
46

C# 7.0 was released with lots of exciting new features. Here in this tutorial, we are going to discuss few of them in a bit detail for our readers including Pattern Matching, Tuples, ref Returns and Locals, Out variables and Local functions.CSharp-New Features

New Features in C# 7.0

<!– TopRight336by280 –> // &lt;![CDATA[
(adsbygoogle = window.adsbygoogle || []).push({});
// ]]&gt;

Pattern Matching:

Pattern matching is a feature that enables you to implement method dispatch on properties aside from the type of an object. You are most likely already aware of method dispatch based on the type of an object. In Object oriented programming, virtual and override methods give language syntax to implement method dispatching based on an object’s type. Base and Derived classes give totally different implementations. Pattern matching expressions extend this idea so you’ll be able to easily implement similar dispatch patterns for types and data elements that don’t seem to be connected through an inheritance hierarchy.

Pattern matching supports expressions and switch expressions. Every expression allows checking an object and its properties to see if that object satisfies the needed pattern. We can utilize the keyword to specify extra rules to the pattern.

The pattern expression extends the acquainted operator to question an object on the far side of its type. Let’s begin with an easy situation. We’ll add capabilities to the present situation that demonstrate how pattern matching expressions create algorithms that work with unrelated types in a simple manner? We’ll begin with a method that computes the sum of various die rolls:

public static int DiceSum(IEnumerable<int> values)
{
 return values.Sum();
}


You might quickly realize that you just need to know the sum of die rolls where some of the rolls are created with more than one die. A part of the input sequence could also be multiple results rather than one number:

public static int DiceSum2(IEnumerable<object> values)
{
 var sum = 0;
 foreach(var item in values)
 {
 if (item is int val)
 sum += val;
 else if (item is IEnumerable<object> subList)
 sum += DiceSum2(subList);
 }
 return sum;
}

Tuple:

C# provides a good syntax for classes and structs that are accustomed to justifying your style intent. However, that good syntax needs further work with the lowest benefit. You will usually write methods that require an easy structure containing over one data element. To support these situations tuples were added to C#. Tuples are light-weighted data structures that contain multiple fields to show the data members. The fields aren’t validated, and you can’t define your own methods.

A tuple can be created by assigning each member to a value:

var alphabets = ("a", "b");


That assignment creates a tuple whose members are Item1 and Item2, following the present Tuple syntax. You’ll be able to modify that assignment to form a tuple that gives semantic names to every of the members of the tuple:

(string Alpha, string Beta) namedAlphabets = ("a", "b");


The new tuples features need the System.ValueTuple type. For Visual Studio 2017, you need to add the NuGet package System.ValueTuple, out there on the NuGet Gallery.

The above examples show the fundamental syntax to declare tuples. Tuples are most helpful as return types for private and internal methods. Tuples give an easy syntax for those methods which return multiple distinct values. Creating a tuple is a lot of economical and more productive. It’s a much easier, light-weighted syntax to outline a data structure that carries more than one value at the same time. The instance method shown below returns the minimum and maximum values found in a sequence of integers:

private static (int Max, int Min) Range(IEnumerable<int> numbers)
{
 int min = int.MaxValue;
 int max = int.MinValue;
 foreach(var n in numbers)
 {
 min = (n < min) ? n : min;
 max = (n > max) ? n : max;
 }
 return (max, min);
}

ref returns and locals:

C# 7.o adds the power to return by reference and to store references to native variables.

The advantage of using ref returns and ref locals is performance and to make helper methods that weren’t attainable before C# 7. Now you can avoid copying the big struts and reference these directly in safe code.

There are some restrictions on the usage of ref returns and ref locals to stay things safe:

Returned refs should point at changeable (not readonly) object fields, or are passed in by reference ref locals can’t be mutated to point at a distinct location.


public class Point
{
 private int value = 5;
 
 public ref int Get()
 {
 return ref this.value;
 }

 public void Print()
 {
 Console.WriteLine($"Point: {this.value}");
 }
}

public void test1()
{
 var point = new Point();

 ref int highpoint = ref point.Get();
 int anotherPoint = point.Get();

 point.Print();
 Console.WriteLine($"Highpoint: {highpoint}");
 Console.WriteLine($"Another Point: {anotherPoint}");
 highpoint = 10;
 anotherPoint = 20;
 this.change(highpoint);
 point.Print();
 Console.WriteLine($"Highpoint: {highpoint}");
 Console.WriteLine($"Another Point: {anotherPoint}");
}
public void change(int value)
{
 value = 30;
}

out Variables:

Earlier, declaration and initialization of out variables was needed to be done separately as below example:

int Result;
if (int.TryParse(input, out Result))
 WriteLine(numericResult);
else
 WriteLine("Could not parse input");


Now it is no longer needed to declare out variable separately, int can be declared in the argument list of the method call as below example:

if (int.TryParse(input, out int result))
 WriteLine(result);
else
 WriteLine("Could not parse input");


There is also a support for using an implicitly typed variables as below:

if (int.TryParse(input, out var result))
 WriteLine(answer);
else
 WriteLine("Could not parse input");


The advantages of this feature are:

  • Code readability is increased.
  • Initial value assignment is no longer needed.

Local Functions:

Various forms for classes contain methods that are called from only one location. These extra private methods keep every method small and targeted. However, they can create it tougher to know a class once reading it the first time. These methods should be understood outside of the context of the single calling location.

For those styles, native functions provide you to declare methods within the context of another method. This makes it easier for readers of the class to visualize that the native method is just called from the context within which it is declared.

There are two quite common use cases for native functions:

public iterator methods and public async methods. Each forms of methods generate code that reports errors later than programmers may expect. In the case of iterator methods, any exceptions are discovered only if calling the code that enumerates the returned sequence. In the case of async methods, any exceptions are solely discovered once the returned Task is expected.

public static IEnumerable<char> Subset(char start, char end)
{
 if ((start < 'a') || (start > 'z'))
 throw new ArgumentOutOfRangeException(paramName: nameof(start), message: "start must be a variable");
 if ((end < 'a') || (end > 'z'))
 throw new ArgumentOutOfRangeException(paramName: nameof(end), message: "end must be a variable");

 if (end <= start)
 throw new ArgumentException($"{nameof(end)} must be greater than {nameof(start)}");
 for (var c = start; c < end; c++)
 yield return c;
}


C# Unity Developer

We will keep adding more C# 7 features details later to this tutorial. Keep in touch.

More Web Development Related Tutorials:

Top 10 Interview Questions and Answers Series:

The post Top New Features in C# 7.0 appeared first on Web Development Tutorial.

LEAVE A REPLY