User Tools

Site Tools


Tuples in C#

They can hold sets of elements of different types. They are useful when returning more than one value from a method or with creating collections of value pairs. Tuples are reference types

Example: Instantiate a tuple:

// via constructor
var t = new Tuple<int, string>(256, "Test");
// via the static factory method
Tuple<int, string> t = Tuple.Create(256, "Test");

Example: Access properties of a tuple:

var t = new Tuple<int, string>(256, "Test");
Console.WriteLine(t.Item1 - 150);       // 106
Console.WriteLine(t.Item2.ToUpper());   // TEST

Example: Compare tuples (the Equals method is overridden to compare individual elements):

var t1 = Tuple.Create(256, "Test1");
var t2 = Tuple.Create(256, "Test1");
Console.WriteLine(t1 == t2);       // false - t1 and t2 reference to different objects
Console.WriteLine(t1.Equals(t2));  // true

Example: Return Tuple<int, int> from a method:

public Tuple<int,int> Divide(int dividend, int divisor)
    int result = dividend / divisor;
    int reminder = dividend % divisor;
    return Tuple.Create<int,int>(result, reminder);
Tuple<int, int> n = Divide(7, 3);
Console.WriteLine($"result: {n.Item1}, reminder: {n.Item2}"); // result: 2, reminder: 1

Example: Create a tuple with more than eight parameters by passing a tuple as the last template parameter (called TRest). This technique can be used to create a tuple with any number of items:

var tuple = Tuple.Create<string, string, string, int, int, int, double, Tuple<int,int>>(
    "Racoon", "Possum", "Groudhog", 
    250, 3400, 8, 1.67, 
    Tuple.Create<int, int>(55, 881));
notes/csharp/tuples.txt · Last modified: 2016/12/14 by admin