Editorials

Trying on Tuples

I have recently become reacquainted with one of the cool generic techniques found in .Net, tuples. Tuples allow you to pass data in a structured form without fully defining a class or struct to pass complex object.

If I had the need to pass an integer identifier, a phone number, and an Email address I could create a class with that structure. Using a language such as C# it might look like

public class myStuff

{

public int Id { set; get; }

public string PhoneNumber { set; get; }

public string Email { set; get; }

}

Now I can pass around this complex type by instantiating an instance of myStuff. But what if I want to create a method returning more than one value, and the values are really not being used throughout my system? Do I still need to create a special class or struct? Tuples to the rescue. Here is a method that returns those same three data attributes, strongly typed, without the heavy lifting of a class definition.

public Tuple<int, string, string> GetMyStuff(int id)

{

return new Tuple<int, string, string>(1, "310.630.1827", "btaylor@sswug.org");

}

Now I can consume the results by calling this method. The call returns one variable with three properties of different types referenced by their ordinal position in the Tuple definition.

public void ShowData()

{

var result = GetMyStuff();

Console.WriteLine("ID: {0}", result.Item1);

Console.WriteLine("Phone Number: {0}", result.Item2);
Console.WriteLine("Email Address: {0}", result.Item3);

}

Does it make sense to use Tuples? Don’t mistake the lack of naming for lack of strong typing; attributes are not an object or variant data type. Classes demonstrate intent much better because the consumer references actual properties with names other than ordinal references. Would you or do you use Tuples? Do you have any guidelines for those interested in trying them on for size?

As always, you can get into the conversation by leaving your comments here or sending them to btaylor@sswug.org.

Cheers,

Ben