Monday, December 26, 2011

Tuple: Return multiple values from function

How do you return multiple values from function?

Option 1: use out parameters. But this will just bloat your function signature if the list is long
Option 2: Encapsulate all return values as properties of class and just return the object of that class. But what if that class is not reusable. Will you be just adding the dumb classes to increase assembly size and abusing the OOPs.

Here comes the solution "Tuple" in .NET 4.

By using Tuple type you can return upto 8 items at a time. These items could be value type or reference type.



Actually if you use the instance approach, you can pass a tuple inside Tuple. That means you can return a tuple of any number of items.







There are few points to note though
1. tuple items are read only (there is no set accessor for items). That makes its items immutable.
2. The items can be accessed by using "Item" property. For e.g. to access 2nd item, you have to call myTuple.Item2.

let's take an scenario where you need this kind of structure

 public static Tuple<string,string,string,string> GetAny4ItemsOnMyDesk()
        {
            //Instance approach
            return new Tuple<stringstringstringstring>("Laptop""Phone""Notebook""Pen");
 
            //By using static method
            //return Tuple.Create("Laptop", "Phone", "Notebook", "Pen");
 
        }

This is clear in the above example that you will not like to create a dumb class to contain "unrelated" things. Actually Tuple stucture can be used to contain "miscellaneous but related" items.

Now lets print my desk items from Main

static void Main(string[] args)
        {
            var ItemsOnMyDesk = GetAny4ItemsOnMyDesk();
            StringBuilder sb = new StringBuilder();
            sb.Append("Item 1: " + ItemsOnMyDesk.Item1);
            sb.AppendLine();
            sb.Append("Item 2: " + ItemsOnMyDesk.Item2);
            sb.AppendLine();
            sb.Append("Item 3: " + ItemsOnMyDesk.Item3);
            sb.AppendLine();
            sb.Append("Item 4: " + ItemsOnMyDesk.Item4);
            sb.AppendLine();
            Console.WriteLine(sb.ToString());
          
            Console.ReadLine();
 
        }

This will print my 4 items on my desk.

You can use other data structures like keyvaluepair, collection, array etc to serve same purpose. tuple is like anonymous class generated on compile time so its object resides on heap only which gives you struct kind of datastructure out of the box.
Tuple type is widely used in functional language like "Haskell" and dynamic language like "Python. Since it is of finite size and immutable structure, it is faster than list and performs better than keyvaluepair struct when passed to a function (though data retrieval is faster in keyvaluepair).

Thanks for reading.