Search code examples
c#arraysargumentsref

Pass reference array as argument in c#


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);
        }
    }

}


Solution

  • 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).