New features of C# 7

20 Apr 2017

C# 7 has introduced new features which are currently supported by Visual Studio 2017.

Out variable:

Currently, we would require at least two statements to use the out keyword - first one in the declaration statement and next in the method parameter with out keyword (initialization).

/* Before */

int num; // declaration
if (int.TryParse(input, out num)) // out keyword in method param
{
  //Do something
}
C#
/* C# 7 */
if (int.TryParse(input, out int num)) // out keyword in method param
{
  //Do something
}
// The out variable can be accessed outside of the scope of if block
C#

 Since the declaration and initialization happens at same place it gives clarity, as well as it makes sure that the variable is assigned before subsequent use.

Tuples:

Tuple is a lightweight data structure that can contain multiple fields like classes, with simple syntax.

/* Before */
var ab = ("a", "b");

//Accessing
Console.WriteLine(ab.item1 + "," + ab.item2);
C#
// With C# 7, we can have semantic names for each item in the tuple
(string A, string B) ab = ("a", "b");
// or var ab = (A: "a", B: "b");

//Accessing
Console.WriteLine(ab.A + "," + ab.B);
C#

There were many situation were we would need to return more than a single result from a method and it too simple that it doesn't need a complex Class. Usually we would go with an Array or list structure. But now with named Tuple, you can return multiple outputs with a semantic names (like classes)

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);
}
C#

The earlier limitation of Tuple creation (prior to C#7) through Create<T1>(T1) is now removed.

IS expression:

As a part of type checking using is, we can initialize it to a matching type. For example

public static int Sum(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 += Sum(subList);
    }
    return sum;
}
C#

Switch Statement supports types :

With C# 7 you can use different types in each cases as below

public static int Sum(IEnumerable<object> values)
{
    var sum = 0;
    foreach(var item in values)
    {
        Switch (item){
            Case int val:
                sum += val;
                break;
            Case IEnumerable<object> subList:
                sum += Sum(subList);
                break;
        }
    }
    return sum;
}
C#

Related Posts