Tuple deconstruction in C# 7

Last time on this blog I talked about the new tuple feature of C# 7. In Visual Studio 15 Preview 3, the feature wasn’t quite finished; it lacked 2 important aspects:

  • emitting metadata for the names of tuple elements, so that the names are preserved across assemblies
  • deconstruction of tuples into separate variables

Well, it looks like the C# language team has been busy during the last month, because both items are now implemented in VS 15 Preview 4, which was released today! They’ve also written nice startup guides about tuples and deconstruction.

It is now possible to write something like this:

var values = ...
var (count, sum) = Tally(values);
Console.WriteLine($"There are {count} values and their sum is {sum}");

(the Tally method is the one from the previous post)

Note that the intermediate variable t from the previous post has disappeared; we now assign the count and sum variables directly from the method result, which looks much nicer IMHO. There doesn’t seem to be a way to ignore part of the tuple (i.e. not assign it to a variable), hopefully it will come later.

An interesting aspect of deconstruction is that it’s not limited to tuples; any type can be deconstructed, as long as it has a Deconstruct method with the appropriate out parameters:

class Point
{
    public int X { get; }
    public int Y { get; }

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public void Deconstruct(out int x, out int y)
    {
        x = X;
        y = Y;
    }
}

...

var (x, y) = point;
Console.WriteLine($"Coordinates: ({x}, {y})");

The Deconstruct method can also be an extension method, which can be useful if you want to deconstruct a type that you don’t own. The old System.Tuple classes, for example, can be deconstructed using extension methods like this one:

public static void Deconstruct<T1, T2>(this Tuple<T1, T2> tuple, out T1 item1, out T2 item2)
{
    item1 = tuple.Item1;
    item2 = tuple.Item2;
}

...

var tuple = Tuple.Create("foo", 42);
var (name, value) = tuple;
Console.WriteLine($"Name: {name}, Value = {value}");

Finally, methods that return tuples are now decorated with a [TupleElementNames] attribute that indicates the names of the tuple members:

// Decompiled code
[return: TupleElementNames(new[] { "count", "sum" })]
public static ValueTuple<int, double> Tally(IEnumerable<double> values)
{
   ...
}

(the attribute is emitted by the compiler, you don’t actually need to write it yourself)

This makes it possible to share the tuple member names across assemblies, and lets tools like Intellisense provide helpful information about the method.

So, the tuple feature of C# 7 seems to be mostly complete; however, keep in mind that it’s still a preview, and some things could change between now and the final release.

10 thoughts on “Tuple deconstruction in C# 7”

  1. It seems odd to add a Deconstruct method, and it is used, without any interface or base class. Are there other examples of this in the language?

    1. Hi Michael,

      Yes, in fact many C# features are pattern-based:

      – foreach loops: relies on the presence of a GetEnumerator method, doesn’t actually require the IEnumerable interface
      – async/await: anything can be awaited as long as it has an adequate GetAwaiter method
      – collection initializer: relies on an Add method, doesn’t need to implement ICollection or IList

      and I’m probably missing a few other cases…

  2. I read in the blog post accompanying the release that they’re planning on a syntax to ignore unwanted tuple elements but it’s not in the current preview and may not make it in time for C# 7.

    The syntax was like

    var (count, *) = Tally(values);

    which would ignore the “sum”

  3. Salut Thomas!
    I’m Agostino, a .net developer base in Milan.
    I discovered your blog during these days, and I find it very interesting!
    I noticed you have both an english and french version of your blog,
    and that’s something I was thinking about to do right during these days:
    I have sooooo many questions about that!!! :Do

    how do you manage them?
    Do you start writing your articles in french and after you translate them
    to your english blog?
    Do you use google translator to automate this translation process, or do you
    “manually” translate them ?
    Which of them do you consider your primary blog to treat?
    Do you consider your french blog to have locally visibility,
    and your english blog to have international relations?
    Which of them gets more traffic?

    Sorry mate, but I’m a very curious person and I love learning from
    experienced people.

    Merci beaucoup!:)
    Have a nice day,
    Agostino

    1. Hi Agostino,

      Thanks for your comment.

      how do you manage them?

      I use WordPress with the multisite option. Basically I have two blogs, each mapped to its own domain.

      Do you start writing your articles in french and after you translate them
      to your english blog?

      That’s what I did when I started, but it didn’t really work well, because the English version didn’t feel very natural – you could easily tell that it was a translation. Now I do the opposite: I write the English version first, then I translate it to French.

      Do you use google translator to automate this translation process, or do you
      “manually” translate them ?

      I do the translation manually. Automatic translation tools give terrible results, in my experience.

      Which of them do you consider your primary blog to treat?

      The English one, since it has a much larger audience.

      Do you consider your french blog to have locally visibility,
      and your english blog to have international relations?

      When I started blogging, I only had the French blog, but I soon realized that I was only reaching a limited audience, so I started blogging in English as well. Now I maintain the French version only for the benefit of French-speaking people who are not fluent in English.

      Which of them gets more traffic?

      The English one, by far. My French blog has only about 40 visits per day, while the English one has about 700.

  4. Thank you so much Thomas,
    you helped me a lot to understand what’s needed to work in that direction and what I really want to get.
    Have a great day,
    Agostino

Leave a Reply

Your email address will not be published. Required fields are marked *