Monday, October 10, 2016

Tuples in C# 7

Tuples has been there since the release of .NET 4.0 and it was mostly used for returning more than one value from a method. With C# 7.0, there are couple of new improvements coming around Tuples. Let’s see what those are.

Before C# 7, use of Tuples basically is as follows.
static void Main(string[] args)
{
    List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
    var values = GetValues(numbers);
    Console.WriteLine($"min:{values.Item1}, max:{values.Item2}, sum:{values.Item3}");
}
 
static Tuple<int, int, int> GetValues(List<int> numbers)
{
    return new Tuple<int, int, int>(numbers.Min(), numbers.Max(), numbers.Sum());
}
So what's not so good with this? First you need to create a new instance of a Tuple before returning. Then you can’t name the single elements, thus you are limited to access the returned elements by Item1, Item2 etc.

With C# 7, following is possible.
static void Main(string[] args)
{
    List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
    var values = GetValues(numbers);
    Console.WriteLine($"min:{values.min}, max:{values.max}, sum:{values.sum}");
}
 
static (int min, int max, int sum) GetValues(List<int> numbers)
{
    return (numbers.Min(), numbers.Max(), numbers.Sum());
}
Here you can specify the names for the individual elements inside the returning Tuple and no object creation is needed. If you are comfortable with no names, you can still omit the names and access elements by Item1, Item2 etc.
static (int, int, int) GetValues(List<int> numbers)
{
    return (numbers.Min(), numbers.Max(), numbers.Sum());
}
Or you can always me more specific.
static (int min, int max, int sum) GetValues(List<int> numbers)
{
    return (min: numbers.Min(), max: numbers.Max(), sum: numbers.Sum());
}
You can even use some other names when you are declaring the Tuple and doing the deconstruction.
var (_min, _max, _sum) = GetValues(numbers);
(var _min, var _max, var _sum) = GetValues(numbers);
Isn’t that great?

And do keep monitoring what's happening on C# 7,
https://github.com/dotnet/roslyn/issues/2136

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment