kota's memex

A tuple is a simple composite type that joins multiple pieces of data into a single element:

(string, int, int) score = ("Kota", 12420, 15);
Console.WriteLine($"Name:{score.Item1} Level:{score.Item3}, Score:{score.Item2}");

Order

A tuples parts are ordered so (string, int) is different than (int, string):

(string, int, int) score1 = ("Kota", 12420, 15);
(string, int, int) score2 = score1; // An exact match works.

Element names

The names of the items in a tuple are by default Item1, Item2, etc. You can assign aliases when creating the tuple:

(string Name, int Points, int Level) score = ("Kota", 12420, 15);
Console.WriteLine($"Name:{score.Name} Level:{score.Level}, Score:{score.Points}");

Usage in methods

You can pass a tuple as an argument or return a tuple from a method:

var score = GetScore();
DisplayScore(score);

(string Name, int Points, int Level) GetScore()
{
	return ("Kota", 100, 12);
}

void DisplayScore((string Name, int Points, int Level) score)
{
  Console.WriteLine($"Name:{score.Name} Level:{score.Level}, Score:{score.Points}");
}

Deconstruction

Quickly converting a tuple into individual variables:

var score = (Name: "Kota", Points: 100, Level: 15);

string name;
int points;
int level;
(name, points, level) = score;

You can even declare the variables at the same time, which looks dangerously close to declaring a new tuple:

(string name, int points, int level) = score;

The only difference is that there is no name after the parenthesis to refer to the tuple.

Variable swapping

This a common, slightly clever usage of a tuple:

int x = 1;
int y = 2;
(x, y) = (y, x);