C# Support for Tuples

by Miguel de Icaza

More Mono proof of concept extensions to C#.

As part of the list of things I would like to see in C# is support for tuples in the language. They would show up in a few places, for example, to return multiple values from a function and assign the results to multiple values at once.

In recent versions of the framework there is a new datatype called Tuple, it is used to hold N values, the Tuple for N=2 looks like this:

	public class Tuple<T1, T2> {
		public Tuple (T1 v1, T2 v2);
		T1 Item1 { get; set; }
		T2 Item2 {get; set; }

The tuple patch extends the C# language to allow multiple variables to be assigned from any Tuple, like this:

	(user, password, host, port, path) = ParseUri (url);

The above would assign the four values to user, password, host, port and path from the call to ParseUri. ParseUri would be declared like this:

	Tuple<string, string, string, int, string> ParseUri (string url);

Future Work and Ideas

In addition to handling Tuples, I would like to extend this to support collections and IEnumerables as well, for example:

	(section, header) = my_array;

The above would store my_array [0] in section, and my_array [1] in header.

If the last element of a tuple is a collection, it could store the rest of the values from the collection or enumerable in the last element:

	(query, page, other_options) = Request.QueryString;

The above would store the first item in the QueryString into query, the second into page, and the rest into the other_options array.

Tuple creation syntax:I would like to add nicer support for creating Tuples as return values, it could just mirror the assignment syntax.

	ParseUri ()
		return (user, password, host, port, path);

Handling well-known types: In addition to Tuple, ICollections and IEnumerables, perhaps the compiler should know about older versions of Tuple like DictionaryEntry.

Using statements: Today the using statement is limited to a single resource, with multi-valued return types, it could handle multiple resources at once, like this:

	using (var (image, audio, badge) = iphoneApp.GetNotifications ()){
	    // use IDisposable image
	    // use IDisposable audio
	    // use trivial int badge

Posted on 23 Dec 2009