Monday, May 25, 2009

Tuple in C# 4.0

Tuple is defined as a Sequence (or ordered list) of finite length. Other definitions exist but I particularly like to see it as such.

I have been craving for this feature ever since seen in Cw(C-Omega). This is particularly useful when you want to return multiple values from a function/method especially when they are not related enough to want to put then in a class or struct. Some developers like myself result to using multiple out parameters. This gets messy for methods that have return type and so inconsistence in returning values from such methods.

   1: var x = DoSomething(out int a, out int b);




The compiler is smart enough to detect when you have unmatched number of arguments





   1: var myTuple = new Tuple<int, int, int>(0, 1); 




or request for a member beyond it's definition





   1: Console.WriteLine(myTuple.Item4); 




Tuples in C# 4.0 lacks the ability to get the Length/ Count/Size value even though the underlying interface ITuple specifies this. I guess the C# team pulled this out to prevent us from seeing or using this as an Array or Collections.



In the Beta 1 Release, I tried getting my hands dirty with this and was shocked on a discovery. Something about an error on the eight argument of a tuple being requeired to be ITuple. I searched online for this and came across an interesting Post about infinite Tuple (Tuple with eight parameters in constructor)






   1: Tuple<int, int, int, int, int, int, int, int> 




http://blog.dynamicprogrammer.com/2009/05/25/TupleANewTypeOnNet40.aspx

2 comments:

Unknown said...

More info on how the CLR handles Tuple and the challenges faced by the CLR team

http://msdn.microsoft.com/en-us/magazine/dd942829.aspx

Anonymous said...

Good dispatch and this fill someone in on helped me alot in my college assignement. Gratefulness you seeking your information.