Sunday, August 1, 2010

Tuple in C# 4.0



What is a Tuple?

In Mathematics, A Tuple is a sequence of finite length. An n-tuple is a tuple with n elements. For example (2, 4, 3, 8) is a 4-tuple.

C# 4.0 introduced new data type Tuple. Tuple is not new in software engineering, but of course it is new in dot net frame work 4.0. A tuple is a simple generic data structure that holds an ordered set of items of heterogeneous types. There are two ways to instantiate Tuple By calling either the Tuple constructor or the static Tuple.Create() method.


// Instantiate using constructor
Tuple<int, string, int> t1 = new Tuple<int, string, int>(3, "Frank", 9);

// Instantiate using create method
Tuple<int, int, int> t2 = Tuple.Create(3, 5, 9);



Tuple constructor and create() method can contains maximum 8 parameters. You have to take care of the 8th parameter because it replaces another tuple object.


Simple use of Tuple


You can easily return more than one value from Method without using out or ref parameters.


public Tuple<int, int> SplitPoints(string point)
{
string[] pointList = point.Split(',');

int x = Convert.ToInt32(pointList[0]);
int y = Convert.ToInt32(pointList[1]);
return Tuple.Create<int, int>(x, y);
}


SplitPoints method split the points and returns x and y points in tuple.


Tuple<int,int> points = SplitPoints("12,14");
string msg = string.Format("X: {0}, Y: {1}", points.Item1, points.Item2);
MessageBox.Show(msg);



You can get returned values from exposed properties Item1, Item2 etc by Tuple object. Item properties of Tuple object are readonly. You can not change the value of the property.

1 comment:

  1. Good Post.
    I recently stumbled on an article of yours on codeproject, it was about tier generator. If you were the one who really developed that application then I owe you a world of thanks. I was able to complete numerous projects, in a short time and be an hero, with that application. Great job and I am searching feverishly for other applications of yours. another thing: you mentioned that you would improve on tier generator but I have yet to find an update. I guess you dropped the project, but if not let me know.
    About the above post: what are the benefits of tuple over...lets say...arrays in a similar case like the above example (returning multiple numbers).

    ReplyDelete