DEV Community

Jared Mathis
Jared Mathis

Posted on

2 1

C# Tuples

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).

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay