Tuesday, September 14, 2010

Using the Tuple in C# and .NET 4

A new feature in C# for .NET 4 is the Tuple type.  A tuple, in C#, is a group of up to eight items of any type.



var aTuple = 
    new Tuple<string, DateTime>("This is a log entry", DateTime.Now);

I have found this to be a good, direct replacement for methods that take "out" parameters as arguments.  The following example shows a method that returns a list of messages and the total number of messages.

Example 1

public int GetMessages( out IList<string> Messages)
{
  Messages = new List<string>{"hello", "goodbye"};
return 2;
}

var aMessages = new List<string>();
var aCount = GetMessages(aMessages);
var aMessage = aMessages[0];

I prefer my code to be as direct as possible.  I can use a tuple to return multiple types and directly assign the results in my calling code.

Example 2
public Tuple<int, IList<string>> GetMessages()
{
  return new Tuple<int, IList<string>>(2, new List<string>{"hello", "goodbye"});}
}

var aMessages = GetMessages();
var aMessage = aMessages.Item2[0];     // Item2 is the second item in the tuple

Example 2 eliminates a degree of indirection that makes code harder to follow.  In Example 1 I have to infer how aMessages was populated by the program.  If I don't have source code for the GetMessages method in Example 1 that inference might take a little while to get.

For me, direct code is nicer because of its simplicity.  I like simple, direct code because it tends to reduce the number of defects in my projects.  The Tuple type helps me simplify my code and I will be using it from now on.



No comments: