Friday, June 25, 2004

Tuples

Often they request tuples support in C#. Actually I will remove all the out parameters from my APIs as soon as tuples have been introduced to C#. But what do we really need?

Tuple is an immutable array of objects. "Objects" means instances of type System.Object. Thus method returning tuple has type object[]. This behavior does not require any language change. If someone wishes the method to return something like (int x, int y, Color c) he|she should rethink the model and declare

struct Pixel{ int x, y; Color c }

What tuples actually provide is multiple assignment:

int [] F( string str )
{
string [] ss = str.Split();
int [] result = new int[ ss.Length ];
for( int i = 0; i < ss.Length; i++ )
result[i] = int.Parse(ss[i]);
return result;
}
int a, b;
(a,b) = F( "3 5" ); // assures a=3 and b=5;
(a,b) = (b,a); // swap a and b

That is unrolling of array to a sequence of variables with casting and coercion if needed. Reverse operation is needed to support the last statement of swapping two variables. That is the comma operator which combines objects to an array.

One question is what should happen in the following situation:

(a,b) = F( "3 5 7 9" );

Extra objects could be dropped or an exception could be raised. In the latter case the exception should be thrown after assigning to a and b. Thus there will be a chance to simply ignore the exception:

try { (a,b) = F( "3 5 7 9" ); }
catch(ExtraObectException){};

There could be a way of handling all the extra objects with an array:

int [] others;
(a,b,others) = F( "3 5 7 9" );
// a=3 and b=5 and others = new int[]{7,9}

I have placed parenthesis around tuples a,b after I had written the article. I feel the need of the parenthesis to prevent ambiguity in method calls:

void M( int [] );
void M( int, int, int );
M( 3,4,5 );
M( (3,4,5) );

And one note: IMO tuples are not needful.


Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?