loading...

C# Tuples

jaredmathis profile image Jared Mathis ・1 min read

Beginning with C# 7.0, Tuples can be expressed like this:

(double, int) t1 = (4.5, 3);
Console.WriteLine($"Tuple with elements {t1.Item1} and {t1.Item2}.");
// Output:
// Tuple with elements 4.5 and 3.

(double Sum, int Count) t2 = (4.5, 3);
Console.WriteLine($"Sum of {t2.Count} elements is {t2.Sum}.");
// Output:
// Sum of 3 elements is 4.5.

This way you don't have to write new Tuple(item1, item2).

Tuples can be expressed succintly in method signatures. For example, this method returns an IEnumerable of tuples of generic type T:

public static IEnumerable<(T,T)> Pairs<T>(IEnumerable<T> ts)
{
    var skip = 1;
    T previous = default;
    foreach (var current in ts)
    {
        if (skip == 0)
        {
            yield return (previous, current);
        }
        else
        {
            skip--;
        }
        previous = current;
    }
}

This method enumerates through pairs of an IEnumerable.

For example, if you have new [] { 1,2,3 }, the following tuples will be enumerated (using the new syntax): (1,2), (2,3).

Discussion

pic
Editor guide