1
votes

I am trying to pass an array of doubles into a mehtod in another class that will some calculations and return another array of doubles.

Here is how I am currently calculating it.

private void btnCalcLGM_Click(object sender, EventArgs e)
    {    
        public double[] myInputArray = {455.0,400.0,300.0,200.0,100.0};
        LogisticGrowthDCA prodArray = new LogisticGrowthDCA (myInputArray);
    }

And here is the class and method I am trying to call.

public class LogisticGrowthDCA
{
    private double defaultK = 500000;
    private double defaultA = 50;
    private double defaultN = .5;

    public double[] myArray;

    public LogisticGrowthDCA(double[] myInputArray)
    {            
        for (int i = 0; i< myInputArray.Length; i++)
        {
            myArray[i] = myInputArray[i]; //do some calculation
            return myArray;
        }
    }
}

It says I am getting errors like: "A field initializer cannot reference the non-static field, method, or property 'DataAccessProject.Form1.myInputArray'"

How do I return an array from my method and why can't I pass an array into the method?

2
Access specified within the button click event... public double[] ... Looks fishy. Try removing that - David Chelliah
Thanks, I moved it outside the button click event. - dont_break_the_chain

2 Answers

1
votes

You cannot declare a variable with access modifier inside a method. i.e public

double[] myInputArray = {455.0,400.0,300.0,200.0,100.0};

Additionally, You cannot return anything when creating an object. (When using a constructor).

public LogisticGrowthDCA(double[] myInputArray)
{            
    for (int i = 0; i< myInputArray.Length; i++)
    {
        myArray[i] = myInputArray[i]; //do some calculation
    }
}
0
votes

There are couple mistakes in your code as below

first you can't have access modifier like public/private/protected for local method variable. Moreover, declaring them as public won't make sense sice their scope limited within the method block.

public double[] myInputArray = {455.0,400.0,300.0,200.0,100.0};

Second in your class LogisticGrowthDCA constructor you are trying to return an array (as pointed below) which is not possible cause constructor are meant for field initialization and so doesn't return anything and are kind of void type always by default.

public LogisticGrowthDCA(double[] myInputArray)
{            
    for (int i = 0; i< myInputArray.Length; i++)
    {
        myArray[i] = myInputArray[i]; //do some calculation
        return myArray; <-- HERE
    }
}

Read about Constructor in C# Programming for more information.