0

I create 2 jagged arrays inside my function:

double[][] x = new double[i][];
double[][] y = new double[j][];

I perform some sort of operations on them, and want to return both of them as a result of the function. How can I do that?

2 Answers 2

4

Well you could return an array of jagged arrays: double[][][]

public double[][][] GetData(int i, int j)
{
    double[][] x = new double[i][];
    double[][] y = new double[j][];

    return new [] {x, y};
}

but it may make more sense to define a class to give the results context. If you return two arrays what do they mean? Are they always in the same order? By just returning an array you leave a lot for the consumer to learn about the meaning of the return type. A class, on the other hand, would provide context:

public TwoArrays GetData(int i, int j)
{
    double[][] x = new double[i][];
    double[][] y = new double[j][];

    return new TwoArrays {X = x, Y = y};
}

public class TwoArrays
{
    public double[][] X  {get; set;}
    public double[][] Y  {get; set;}
}
Sign up to request clarification or add additional context in comments.

2 Comments

So, should I define a class with 2 fields, each of them a jagged array, create a new object of that class in my function and reurn that object? Like public class MyClass { //fields }, then public static MyClass function(){ MyClass obj1 = new Myclass; //something; return obj1 }?
@Januszoff That would certainly make the purpose of the arrays much clearer - I've added that to my answer.
-1

Tuples are a completely valid option as well. Some folks don't like them as a matter of opinion, and they're NOT great options for public APIs, but they're useful without adding yet another class to your namespace. You can go overboard with them, and four- and five-tuples exceed even my tolerance for them

        double[][] x = new double[i][];
        double[][] y = new double[j][];
        // Work your magic
        return new Tuple<double[][], double[][]>(x, y);

Item1 and Item2 will now be your double[][] arrays.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.