Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to initialize multiple variables from a tuple?

Tags:

c#

tuples

In some languages (such as PHP, Haskell, or Scala), you can assign multiple variables from tuples in a way that resembles the following pseudocode:

list(string value1, string value2) = tupleWithTwoValues;

I can't find a way to do this in C#, however, without writing longer, uglier code:

string firstValue = tupleWithTwoValues.Item1;
string secondValue = tupleWithTwoValues.Item2;

This two-line solution is obviously not the end of the world, but I'm always looking for ways to write prettier code.

Does anyone know a better way to do this?

like image 303
Micah Avatar asked Jan 02 '14 22:01

Micah


1 Answers

This is now available in C# 7:

public (string first, string last) FullName()
{
    return ("Rince", "Wind");
}

(var first, var last) = FullName();

You can even use a single var declaration:

var (first, last) = FullName();

More on destructuring tuples in the official documentation.

like image 139
badteeth Avatar answered Oct 05 '22 23:10

badteeth