C# Static Methods Which Return Multiple Arrays

I was writing some code recently and was surprised to run into a very basic scenario I hadn’t come across before in a C# environment. I had a static method which needed to return two arrays. There were several interesting details. To return two arrays I could use an explicit return value for one result, and use an out or ref mechanism for the second result, or use an out or ref mechanism for both returns. I decided to use the first approach. Here is an example of what I consider the best way:

static double[] Foo (int n, out double[] alpha)
{
  double[] returnResult = new double[n];
  returnResult[0] = 1.1;

  alpha = new double[n];
  alpha[0] = 2.2;

  return returnResult;
}

and then:

double[] alpha = null;
double[] returnResult = Foo(2, out alpha);

The idea is that because the method is returning 2 arrays, both arrays are allocated with “new” inside the method, and I use the “out” parameter keyword. This version also works if I don’t explicitly initialize alpha:

double[] alpha;
double[] returnResult = Foo(2, out alpha);

And also works if I instantiate alpha:

double[] alpha = new double[2];
double[] returnResult = Foo(2, out alpha);

The original version also works if I use the “ref” keyword instead of the “out” keyword, but then alpha must be explicitly instantiated or I get a compiler error.

Another way which works is:

static double[] Foo(int n, double[] alpha)
{
  double[] returnResult = new double[n];
  returnResult[0] = 1.1;

  alpha[0] = 2.2;

  return returnResult;
}

and then:

double[] alpha = new double[2]; ;
double[] returnResult = Foo(2, alpha);

Here I do not use the “out” (or “ref”) keyword and I must allocate space for the second return result array outside the method. But this doesn’t feel right because there’s no clear indication in thed parameter list that the out parameter alpha is going to change. To summarize, when writing a static C# method which returns an array value as part of the method’s parameter list, there are several possible approaches but it seems best to allocate space for the result array inside the method and use the “out” keyword.

Advertisements
This entry was posted in Software Test Automation. Bookmark the permalink.