tags:

views:

84

answers:

4

I am trying to write some code to return an array in C#, but don't know the proper syntax. I think my method is set up correctly, but to set an array to the result of the method is what I'm having difficulty with.

Method Declaration:

double[,] function(double variable)
{
...
code
...

return array
}
+1  A: 

Array is double[]. double[,] is a two dimensional array (matrix).

bjornhol
A: 
public static ANameOfSomeClass
{
    public static double[] SingleDoubleArraryMethodName(double parameterValue)
    {
        double[] values = new double[3];

        values[0] = 1.0;
        values[2] = 1.5;
        values[2] = 1.75;


        return values;
    }

    public static double[,] MultDimDoubleArraryMethodName(double parameterValue)
    {
        double[,] values = new double[2,2];

        values[0,0] = 0.0;
        values[0,1] = 1.0;
        values[1,0] = 2.0;
        values[1,1] = 2.5;

        return values;
    }
}

You could call it like

double[] results = ANameOfSomeClass.SingleDoubleArraryMethodName(1.2);

If you remove the keyword static it becoms

ANameOfSomeClass yourObj = new ANameOfSomeClass();

double[] results = yourObj .SingleDoubleArraryMethodName(1.2);
David Basarab
+4  A: 

Here is an example of how to create the two dimensional array, put some values in it, and return it:

double[,] function(double variable) {
  double[,] result = new double[2,2];
  result[0,0] = 1.0;
  result[0,1] = 2.0;
  result[1,0] = 3.0;
  result[1,1] = 4.0;
  return result;
}

If it is a one dimentional array that you want (the question is a bit unclear about that):

double[] function(double variable) {
  double[] result = new double[3];
  result[0] = 1.0;
  result[1] = 2.0;
  result[2] = 3.0;
  return result;
}
Guffa
So outside of the method, how can I set an array variable to the result of this method
Soo
@Soo: Yes, for example: `double[,] x = function(1.5);` (The parameter is unused in the example above.)
Guffa
Guffa, Using that code results in an error that reads:An object reference is required for the non-static field, method, or property
Soo
Then you are using a non-static member in a static context. Are you calling the method `function` from a static method?
Guffa
Yes. How can I work around this? I'm very new to C#, so this is all a bit confusing to me.
Soo
@Soo: if function doesn't use any non-static members of the this object, then make it static as well. e.g. static double[,] function (double n) { ... }
Ben Voigt
Ben, that worked perfectly. I'm going to give the "Check Mark" to Guffa's response as your answer was within that response. Thanks everyone!
Soo
A: 

Guffa's answer illustrates how to create and populate a two-dimensional array (which it looks like is what you want to do).

To set a variable to the return value of this method, you would do this (supposing the method's name were MyMethod):

double myVariable = 12.34;
double[,] myArray = MyMethod(myVariable);
Dan Tao