4

In Python we can unroll a tuple with similar syntax:

a, b = (1, 2)

Is there are similar structure in C#? Or accessing elements like:

Tuple<int, int> t = Tuple.Create(1, 2);
Console.Write(t.Item1);

the only possible way?

2
  • 1
    *Not related but swift also support that. ( Also ES6) Commented Feb 1, 2015 at 11:07
  • 2
    PS , the term is called destructuring Commented Feb 1, 2015 at 11:17

1 Answer 1

5

Tuple destructuring (sometimes called "explosion"), i.e. distributing its elements over several variables, is not directly supported by the C# language.

You could write your own extension method(s):

static void ExplodeInto<TA,TB>(this Tuple<TA,TB> tuple, out TA a, out TB b)
{
    a = tuple.Item1;
    b = tuple.Item2;
}

var tuple = Tuple.Create(1, 2);
int a, b;
tuple.ExplodeInto(out a, out b);

The above example is just for pairs (i.e. tuples with two items). You would need to write one such extension method per Tuple<> size/type.

In the upcoming version of the C# language, you will likely be able to declare variables inside an expression. This might then possibly enable you to combine the last two lines of code above into tuple.ExplodeInto(out int a, out int b);.

Correction: Declaration expressions have apparently been dropped from the planned features for C# 6, or at least restricted; as a result, what I suggested above would no longer work.

Sign up to request clarification or add additional context in comments.

4 Comments

It will be problematic with (1,2...n)
@RoyiNamir: (1,2,...,n) is not valid C# syntax. But if you mean by that a tuple of any length: You will need one extension method for each specific number of tuple items. That is, you need one extension method for Tuple<A,B>, one for Tuple<A,B,C>, one for Tuple<A,B,C,D>, etc. (That is the usual pattern in .NET. There are also several tuple types; or several Action<> and Func<> types.)
Of course it's not a valid syntax. I was referring to a variable length :-)
It will be problematic with (1,2...n) Tuple only goes so high msdn.microsoft.com/en-us/library/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.