Introduction of ‘Tuple’ in .NET Framework 4.0

The introduction of ‘Tuple’ in .NET Framework 4.0, really filled in a missing piece in C#. Apart from giving us the ability to interoperate with functional languages like F# or Python/Ruby, it does offer the convenience of a heterogeneous collection which can take a form of any class or structure that you would have created otherwise. In C#, I feel Tuple syntax is still in its early stages and I am hopeful it will take more friendly syntax in next iterations.
MSDN

We need Tuple to talk to F# or Python. Let us assume a scenario where you have some code written in Python and it used tuples there. As a developer, you want to use the code in C#.  What data type you will use to map to the Python’s ‘tuple’. The representation was entirely missing from C#/.NET.  So – to fill this gap, the tuple was launched.

One of the limitations of return parameters from methods is that you can only have one of them. You can, of course, group them together in a class or struct, but to do that just to return parameters is cumbersome. You can use “out” parameters, but that is also inelegant. The Tuple solves that. Now you can return as many parameters as you like. Definitely worth knowing about.
e.g.:
string errormsg;
User user;
bool success = AuthenticationService.GetUser(usercode, out user, out errormsg);

Bad example – We should avoid “out” parameters, because it means we return 2 objects from a method. A method should return only 1 thing, otherwise it is considered as a code smell.

We can refactor the above code to this…

Tuple<bool, User, string> result = AuthenticationService.GetUser(usercode);
Console.WriteLine(“Result {0}  with user {1}”, result.Item1, result.Item2);

Good example – Here the Tuple type replaces the “out” parameter

You can also use Tuple in LINQ query like;

var myActivity = (from activity in loaded.Descendants(“Activity”)
where (int)activity.Attribute(“id”) == 1
select Tuple.Create(
int.Parse(activity.Attribute(“id”).Value),
activity.Attribute(“name”).Value,
DateTime.Parse(activity.Attribute(“eventDate”).Value))).FirstOrDefault();

int id = myActivity.Item1;
string name = myActivity.Item2;
DateTime eventDate = myActivity.Item3; 

Posted in:

Leave a Reply