Sunday, May 8, 2011

Function returning multiple values in C# and Tuple

With DynamicSugar, I proposed a way for function to return multiple values by combining the dynamic keyword and anonymous type. Because anonymous type are internal it is necessary to use an extra step implemented by the method DS.Values().
static dynamic ComputeValues(int value){

    return DS.Values( new { returnValue = true, amount = 2.0 * value, message = "Hello" } );
}

var r = ComputeValues(2);
Console.WriteLine("returnStatus:{0}, amount:{1}, message:{2}", r.returnValue, r.amount, r.message);

//
Yesterday while presenting my talk "What can we learn from Python and JavaScript while programming in C# 4.0?" at code camp CC15 (MA)

Somebody suggested that using C# 4.0 Tuple could be a solution that would offer type checking and intellisense. So today I tried. Tuple do provide a solution for a function to return multiple values, with type checking and intellisense. But there is no way to name the values. We have to stick with Item1, Item2, Item3, which is not as expressive as name like amount or message.
public static Tuple<bool, double, string> ComputeValuesTuple(int value) {

    return new Tuple<bool, double, string> (true, 2.0*value, "Hello");
}

var t = ComputeValuesTuple(2);
Console.WriteLine("returnStatus:{0}, amount:{1}, message:{2}", t.Item1, t.Item2, t.Item3);

//

If type checking is a requirement this is actually not a bad solution.

No comments:

Post a Comment