New Feature In C#: Tuple Types

Often times we want to return more than one value from a method. Until know there wasn't an ideal way to do this so we had to resort to using Out parameters, custom class for holding the values or something else.

Now C# 7.0 provides us with tuple types and tuple literals:

(int, int) SumSubtract(int a, int b) // tuple return type
    int sum = a + b;
int subtr = a - b; return (sum, subtr); // tuple literal }

This method will return two integers which will hold the values for the sum and subtraction of both input integers.

var results = SumSubtract(56,23);
WriteLine($"Sum is {results.sum} {results.subtr}.");

Tuples are value types which means that you can compare them to each other and find out if they are equal, that is they contain the exact same elements.

Published:   6/7/2017 Tags:   c# programming