What is the Tuple class used for?
The Tuple class is used for short-lived objects consisting of multiple values:
var myTuple = new Tuple<string, int>("Ten", 10);
Passing multiple values in a single object
Commonly when you want to pass an object consisting of several values you’d use something like a custom struct or class, or perhaps a generic KeyValuePair object (if you want to pass an object with exactly two data members).
A tuple can contain any number of properties (each generic type parameter results in a read-only property in your tuple object). Each property is automatically named Item1, Item2, Item3 etc:
// Group related data
var myName = new Tuple<string, string, int>("Ted", "Nyberg", "TedNyberg".Length);
// Output name info
Console.WriteLine(
string.Format(
"My full name is {0} {1} which consists of {2} characters, whitespace excluded.",
myName.Item1,
myName.Item2,
myName.Item3));
Tuples are read-only
Tuples are immutable, their properties do not have any setters, so once a tuple is initialized its values cannot be modified:
A tuple is a class, not a struct
This might not seem that important, but it’s still noteworthy that each tuple is in fact a class, meaning it will have to be garbage-collected. This in contrast to custom structs, or objects such as generic KeyValuePair objects which are created as structs by the compiler. Of course, the KeyValuePair comparison is only relevant if your tuple consists of exactly two properties.