[C# 4] Tuples

C# 4 provides a set of generic classes called “Tuple“. A tuple is a data structure that has a specific number of elements in sequence. It represents the ready-made read-only class for multiple properties (generic read-only array).

1. Tuple Classes

A couple of “Tuple” classes are defined in the “System” namespace.

  • public class Tuple <T1>
  • public class Tuple <T1, T2>
  • public class Tuple <T1, T2, T3, T4, T5, T6, T7>
  • public class Tuple <T1, T2, T3, T4, T5, T6, T7, TRest>

 

2. The static “Tuple” Class

The static “Tuple” class is factory class for static methods. It does not represent the tuple data type. It provides the static “Create()” methods to return the tuple object.

public static Tuple<T1> Create<T1>(T1 item1);
public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2);
...

 

3. Creating Tuple Objects (1) – Constructors

The data should be provided when the object is created. The first way is to use the constructor.

Tuple<int, string> product1 = new Tuple<int, string>(1, "Toy"); // id, name

 

4. Creating Tuple Objects (2) – Tuple.Create()

In general, you are going to use the static helper method.

Tuple<int, string> product2 = Tuple.Create<int, string>(2, "TV");

The more concise syntax is to use the implicit typing.

var product3 = Tuple.Create(3, "Radio");

 

5. Reading Values

Each data value is represented by the read-only property called “Item1“, “Item2“, … , “Item7“, and “Rest“.

public T1 Item1 { get; }
public T2 Item2 { get; }
public T3 Item3 { get; }
public T4 Item4 { get; }
public T5 Item5 { get; }
public T6 Item6 { get; }
public T7 Item7 { get; }
public TRest Rest { get; }

Each property is stronly typed so you do not need casting.

var product1 = Tuple.Create(1, "Toy");
Console.WriteLine(product1.Item1 + ": " + product1.Item2);

 

6. Comparing Tuples

Comparing each indivisual elements in tuples can be cumbersome. So the “Equals()” method is overriden.

var product1 = Tuple.Create(1, "Toy");
var product2 = Tuple.Create(1, "Toy");
var product3 = Tuple.Create(2, "Toy");

Console.WriteLine(product1 == product2); // false
Console.WriteLine(product1.Equals(product2)); // true
Console.WriteLine(product1.Equals(product3)); // false

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s