A method that returns multiple doubles can be realized in various ways:
Through out
parameters:
class MyClass
{
static double Add3(double x, out double xp1, out double xp2)
{
xp1 = x + 1.0;
xp2 = x + 2.0;
return x + 3.0;
}
}
Through tuples:
class MyClass
{
static Tuple<double, double, double> Add3(double x)
{
Tuple<double, double, double> ret = new Tuple<double, double, double>();
ret.Item1 = x + 1.0;
ret.Item2 = x + 2.0;
ret.Item3 = x + 3.0;
return ret;
}
Through a class gathering the results:
class MyClass
{
class Result
{
double xp1;
double xp2;
double xp3;
}
static Result Add3(double x)
{
Result ret = new Result
{
xp1 = x + 1.0;
xp2 = x + 2.0;
xp3 = x + 3.0;
}
return ret;
}
}
My impression from the comments to this question is that people in general consider the approach with the extra class as the best practice. However, I wonder if there is a rule of thumb about the implications on run time performance for the three variants.
Does the constructor of the Tuple
or the class take any extra time as compared to the out
parameters?
In particular, does the variant with the out
parameter have any performance advantage in the case that only one of the resulting doubles will actually be used, such as in the following snippet?
double zPlus3 = MyClass.Add3(z, out _, out _)