Tuple in C# 4.0

Posted on 3 801 views

A System.Tuple is static class that allows you to create collection of specific data-typed values.

Values

You can store values like...

Tuple tuple = new Tuple<int, string, string, bool>(1, "Matija", "Božičević", true);
    

...or you can create it in more easy way...

var tuple = Tuple.Create(1, "Matija", "Božičević", true);
    

Retrieving data is also easy:

int id = tuple.Item1;
string firstName = tuple.Item2;
string lastName = tuple.Item3;
bool isDeveloper = tuple.Item4;
    

Have in mind that Tuple is immutable object, so you cannot dynamically change data in Item(s), once Tuple object is created, because it will return you compilation error:
Property or indexer 'System.Tuple<...>.Item1' cannot be assigned to—it is read only!

Arrays

You can also store objects and arrays of data:

Tuple tuple = new Tuple<int[], string[]>(new int[] { 1, 2, 3 }, 
        new string[] { "Matija Božičević", "Al Pacino", "Clint Eastwood" });