-1

dears ,

i had create a method that will retrieve three arrays after filling them using the ref option

the following error is presented "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'"

the code as below. how I can fix it

 namespace ConsoleApp9
{
    class Program
    {
        public static int getarrays(ref string[] patternName, ref int[] loadindex, ref double[] loadFactor)
        {
            int status = 0;
            for (int i = 0; i < 4; i++)
            {
                patternName[i] = "test";
            }
            for (int i = 0; i < 5; i++)
            {
                loadindex[i] = i;
            }
            for (int i = 0; i < 8; i++)
            {
                loadFactor[i] = i/10;
            }
            return status;
        }
        static void Main(string[] args)
        {
            string[] ptt = new string[1];
            int[] index = new int[1];
            double[] factor = new double[1];
            getarrays(ref ptt,ref index, ref factor);
        }
    }

}

Osama
  • 1
  • 1

3 Answers3

0

You are passing arrays with fixed size of 1. Inside your method, you are iterating for 4, 5 and 8 times while your arrays have length of 1. You should make a constants of pttSize, indexSize and factorSize and use them as arrays size and loops length.

0

You are passing arrays of length 1 to the function and then try to access indices greater than 0.

Adapt your Main method to pass arrays of the correct length:

string[] ptt = new string[4];
int[] index = new int[5];
double[] factor = new double[8];
M. Dennhardt
  • 136
  • 7
0

Your arrays all have a size of 1, but your loops go to 4, 5 and 8 respectively. Instead, use the Length property of your arrays in your loops:

for (int i = 0; i < patternName.Length; i++)
{
    patternName[i] = "test";
}

This is helpful, because the size of your array is only located in one place (at the creation of the arrays).

SomeBody
  • 7,515
  • 2
  • 17
  • 33