choba78 choba78 - 4 months ago 19
C# Question

How to deconstruct a tuple back to its original variables

I am calling a method that return a tuple as a workaround for C# async methods not supporting byval async parameters

private async Task< Tuple<List<string>, List<int>>> MyFunction(List<int> inputList){

var stringList= new List<string> ();
var intList= new List<int> ();
return Tuple.Create(stringList, intList);

To create a tuple from two items I use the
method. However there isn't a method to return it back from where I'm calling the method.

private async Task< Tuple<List<string>, List<int>>> CallTupleFunction(){

var intList = new List<int> ();
var myTuple = MyFunction(intList);
var stringList= myTuple[0]; //does not work
intList = myTuple[1]; //does not work



Tuple is not a single class, it is a group of generic classes with identical name. Each class has a list of types associated with its item types, called ItemN. In your case you need

var myTuple = await MyFunction(intList).ConfigureAwait(false);
//                                     ^^^^^^^^^^^^^^^^^^^^^^
// Remove ConfigureAwait in the front end code (winforms, wpf, etc.)
var stringList= myTuple.Item1;
var intList = nmyTuple.Item2;

To address the [] syntax, it is not possible to provide an API that accesses tuple's items with an indexer, because the only possible return type for an indexer would be System.Object. This would be bad for two reasons:

  • Retrieving tuple's elements would require a cast - you would have to write var stringList= (List<string>)myTuple[0], which defeats the purpose of having a tuple in the first place.
  • Retrieving value-type elements would require boxing - this would be a major concern for processing large volumes of data stored as Tuple<,...,>