Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deconstruct a C# Tuple

Tags:

c#

tuples

f#

Is it possible to deconstruct a tuple in C#, similar to F#? For example, in F#, I can do this:

// in F#
let tupleExample = (1234,"ASDF")
let (x,y) = tupleExample
// x has type int
// y has type string

Is it possible to do something similar in C#? e.g.

// in C#
var tupleExample = Tuple.Create(1234,"ASDF");
var (x,y) = tupleExample;
// Compile Error. Maybe I can do this if I use an external library, e.g. LINQ???

Or do I have to manually use Item1, Item2? e.g.

// in C#
var tupleExample = Tuple.Create(1234,"ASDF");
var x = tupleExample.Item1;
var y = tupleExample.Item2;
like image 735
CH Ben Avatar asked Nov 10 '17 06:11

CH Ben


1 Answers

You can use Deconstruction but you should use C#7 for this purpose:

Another way to consume tuples is to deconstruct them. A deconstructing declaration is a syntax for splitting a tuple (or other value) into its parts and assigning those parts individually to fresh variables

So the following is valid in C#7:

var tupleExample = Tuple.Create(1234, "ASDF");
//Or even simpler in C#7 
var tupleExample = (1234, "ASDF");//Represents a value tuple 
var (x, y) = tupleExample;

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: (Tuple deconstruction in C# 7):

public static void Deconstruct<T1, T2>(this Tuple<T1, T2> tuple, out T1 item1, out T2 item2)
{
    item1 = tuple.Item1;
    item2 = tuple.Item2;
}
like image 170
Salah Akbari Avatar answered Oct 07 '22 01:10

Salah Akbari