Search code examples
c#nested-loopsjagged-arrays

How to avoid my array from being reassigned values as I progress through my loop?


Here is my code below-

double[][] geometricReturnsArray = new double[returnsArray.Count][];;
double[] tempGeometricReturns = new double[returnsArray[0].Count];
double return_1 = 0;
double return_2 = 0;

        for (int i = 0; i < returnsArray.Count; i++)
        {
            for (int j = 0; j < returnsArray[i].Count - 1; j++)
            {
                return_1 = returnsArray[i][j + 1];
                return_2 = returnsArray[i][j];
                tempGeometricReturns[j] = ((return_1 - return_2) / return_2) * 100;
            }
            geometricReturnsArray[i] = tempGeometricReturns;
        }

The issue I'm facing in the code is that tempGeometricReturns keeps getting reassigned as i increases. So in the end, all three arrays of geometricReturnsArray have exactly the same values since when tempGeometricReturns gets reassigned, so do the previous values in geometricReturnsArray.

I tried to use lists as well but then I just get a long list of 267 values whereas I'd prefer three arrays of length 90. What else can I try to do?


Solution

  • In your example you will end up with multiple references to the same array in the geometricReturnsArray. Arrays are reference types, so assignments only copy the reference, not the entire array.

    The fix is to create a new array for each outer loop, for example by copying the existing array when doing the assignment

            }
                geometricReturnsArray[i] = tempGeometricReturns.ToArray();
        }
    
    

    or

    for (int i = 0; i < returnsArray.Count; i++)
    {
        double[] tempGeometricReturns = new double[returnsArray[0].Count];
        for (int j = 0; j < returnsArray[i].Count - 1; j++)
        {