Editorials

Tuples

Tuples are one of my favorite Dot Net constructs. I don’t use them much; but when I need a simple complex data type, and don’t want to go through the trouble of creating a new Class or Struct, a Tuple can be quite handy.

A tuple is a generic class and can be defined by declaring each of the attributes by type. Each attribute is then accessed by it’s ordinal position. Here is an example of a Tuple for a person with fields for Prefix, FirstName, Initial, LastName, Suffix.

var Person = new Tuple();

As you can see there is nothing to identify what each of the strings are for. You have a variable Person with 5 string properties. These are accessed in code as Person.Item1, Person.Item2, Person.Item3, Person.Item4 and Person.Item5. This is one of the reasons I don’t use a Tuple very often. You have to remember what Item1-Item5 represent. Moreover, you could use the Person variable to store anything that has 5 string properties such as an USA Mailing Address, (Street 1, Street 2, City, State, Zip). While you could do the same thing with a Class having five string fields, you would be less likely to do that, because the property names prompt you to put appropriate data in them. A Tuple, being more generic, has less of an implication for data constraints.

I like to us Tuples for Mock data, passing complex parameters between objects or methods, or when I needs something quick and dirty. As a result, I don’t often have a lot of Tuples in my code, wanting to clear in my intentions for those who follow.

Check out Tuples when you get a chance. You may find them to be useful from time to time.

Cheers,

Ben